今天給大家寫一篇關(guān)于Less運算符和函數(shù)的less學習教程 ,有什么問題一起探討。
運算符
Less還支持+、-、*、/運算符。但對單位不一致的運算數(shù)進行運算要注意以下兩點:
1. 運算數(shù)與運算符間必須用空格分隔;
2. 以第一個運算數(shù)的單位作為運算結(jié)果的單位;
Less源碼:
// 運算數(shù)與運算符間沒有空格
@fail: 1px +2em;
.fail{
height: @fail;
}
@success1: 1px + 2em;
.success1{
height: @success1;
}
@success2: 2px + 1em;
.success2{
height: @success2;
}
最終輸出:
.fail{
height: 1px 2em;
}
.success1{
height: 3px;
}
.success2{
height: 3em;
}
函數(shù)
Less為我們提供了一個功能強大的內(nèi)置函數(shù)庫,其中絕大部分為顏色處理函數(shù)。下面著重介紹Misc Function中的default函數(shù)、String Function中的escape函數(shù)和顏色處理函數(shù)。
1. default函數(shù)
示例:
// for teenager
.person(@age) when (@age <= 19) and (@age >=13){
height: @age * 10px;
}// for child
.person(@age) when (@age <13){
height: @age * 6px;
}// for adult
.person(@age) when (default()){
height: 180px;
}
.son{
.person(10);
}
.daughter{
person(17);
}
.father{
.person(27);
}
最終輸出:
.son{
height: 60px;
}
.daughter{
height: 170px;
}
.father{
height: 180px;
}
雖然上述示例邏輯上不合理。但可以看出default函數(shù)用于條件控制當中,充當else或switch語句中default的角色。
通過官網(wǎng)提供的綜合示例我們可以更好理解它的用法:
// Less源碼.x {
.m(red) {case-1: darkred}
.m(blue) {case-2: darkblue}
.m(@x) when (iscolor(@x)) and (default()) {default-color: @x}
.m('foo') {case-1: I am 'foo'}
.m('bar') {case-2: I am 'bar'}
.m(@x) when (isstring(@x)) and (default()) {default-string: and I am the default}
&-blue {.m(blue)}
&-green {.m(green)}
&-foo {.m('foo')}
&-baz {.m('baz')}
}
// 最終輸出
.x-blue {
case-2: #00008b;
}
.x-green {
default-color: #008000;
}
.x-foo {
case-1: I am 'foo';
}
.x-baz {
default-string: and I am the default;
}
注意:
1. default函數(shù)必須在條件控制語句當中使用;
2. default函數(shù)可實現(xiàn)比else更復雜的功能,如下:
// Less源碼.mixin(@value) when (ispixel(@value)) {width: @value}
.mixin(@value) when not(default()) {padding: (@value / 5)}
div-1 {
.mixin(100px);
}
div-2 {
/* ... */
.mixin(100%);
}
// 最終輸出:
div-1 {
width: 100px;
padding: 20px;
}
div-2 {
/* ... */
}
2. escape函數(shù)
顧名思義就是對字符串中的特定字符進行編碼,該函數(shù)將對\<space\>, #, ^, (, ), {, }, |, :, >, <, ;, ], [ 和 =字符進行編碼。
3. 顏色處理函數(shù)
顏色處理函數(shù)又分為四大類:顏色定義函數(shù)(Color Definition)、顏色通道值獲取函數(shù)(Color Channel)、顏色通道值修改函數(shù)(Color Operation Function)、混色函數(shù)(Color Blending)。
這里僅僅介紹常用的lighten和darken函數(shù)。
lighten(color, amount) ,color為顏色,amount為增加的亮度值,取值范圍為0-100%。
darken(color, amount) ,color為顏色,amount為減少的亮度值,取值范圍為0-100%。
原文來自:博客園/張來秀