Angularjs入門

angularJs资源
http://www.angularjs.org/
https://www.github.com/angular/
http://www.angularjs.cn/
http://www.ngnice.com/
http://woxx.sinaapp.com/
angularJs下载
http://www.bootcdn.cn/angular.js/
npm install angular

以下走示例仅基于angular1.3.0,高版本不兼容

架子

function Aaa($scope,$rootScope){ //$rootScope全局 ,函数的形参
    $scope.name = 'hello' /* M */
    $rootScope.age = 20; //$scope,只会有Aaa起作用
}}            
<div ng-controller="Aaa" ng-app>
    <p>{{name}}</p>
    <p>{{age}}</p>
</div>

angularJs的MVC方式

数据的挂载
ng-controller
双大括号表达式

angularJs的作用域

$scope
$rootScope
依赖注入
服务

angularJs的指令系统

ng- 指令; ng-app:初始化;,不写则不会执行;初始化可以写到任何位置,按标签来启动 ; ng-controller :控制器连接桥梁;

angular双向数据绑定

MVVM; 当M(数据)发生改变时,会自动让视图改变,而视图改变,可以让相关的数据改变,
$timeout
ng-click
ng-model

数据影响视图

function Aaa($scope,$timeout){ //注入$timeout
    $scope.name = 'hello' /* M */
    $timeout(function(){
        $scope.name = 'hi' /* M */
    },2000)//改变后视图也改 ;

    $scope.show = function () {
        $scope.name = 'hahahas'
    }
}
<div ng-controller="Aaa" ng-click="show()">  <!-- C -->  <
    <p>
        {{name}}  <!-- V -->
    </p>
</div>

视图影响数据

function Aaa($scope,$timeout){ //注入$timeout
    $scope.name = 'hello' /* M */
    $timeout(function(){
        $scope.name = 'hi' /* M */
    },2000)//改变后视图也改 ;

    $scope.show = function () {
        $scope.name = 'hahahas'
    }
}
<div ng-controller="Aaa">  <!-- C -->
    <input type="text" name="" id="" ng-model="name"/>  <!-- 输入框改东西会影响到p标签里的name,ng-model指的即为数据 ; -->
    <p>
        {{name}}  <!-- V -->
    </p>
</div>

过滤器

currency

$watch

监听数据变化
三个参数
function Aaa($scope,$timeout){ //注入$timeout
    $scope.iphone = {
        money:50,
        num:1,
        fre:10
    }
    $scope.sum = function(){
        return $scope.iphone.money * $scope.iphone.num
    }
    $scope.$watch('iphone.money',function(newVal,oldVal){ 
    //  ('字符串(不加$scope)',function(){} ,true) //第三个参数针对集合监听,注意字符串也必须是集合;
    //  console.log(newVal); //监听时iphone.money改变时触发 ;
    //  console.log(oldVal); //监听时iphone.money改变时触发 ;
    // newVal :新值,
    // oldVal:  旧值
    },true) 


    $scope.$watch($scope.sum,function(newVal,oldVal){
        console.log(newVal); //监听时iphone.money改变时触发 ;
        console.log(oldVal); //监听时iphone.money改变时触发 ;
        $scope.iphone.fre =   newVal>=100?0:10; //当大于100时运费免费
    })
}
<div ng-controller="Aaa">  <!-- C -->
    <input type="text" name="" id="" ng-model="name"/>  <!-- 输入框改东西会影响到p标签里的name,ng-model指的即为数据 ; -->
    <p>
       价格:<input type="text" name="" id="" ng-model="iphone.money"/>
    </p>
    <p>个数:<input type="text" name="" id="" ng-model="iphone.num"/></p>
    <p>费用:<span>{{sum()| currency:'¥' }}</span></p>
    <p>运费:<span>{{iphone.fre | currency:'¥'}}</span></p>  <!-- html里的代码不需要写$scope -->
    <p>总额度:<span>{{sum()+iphone.fre | currency:'¥'}}</span></p>
</div>



angularJs的模块化

angular.module
压缩的问题

angularJs的工具方法

angular.bind :是当于$.proxy,改this指向;
angular.copy :复制
angular.extend : 对象的复制,相当于继承
var m1 = angular.module('myApp',[]);
    m1.controller('Aaa',['$scope',function($scope){  //m1.controller控制器(函数名,函数内容)
        $scope.name = 'hello'
    }])
function show(n1,n2){
    alert(n1)
    alert(n2)
    alert(this)
}
angular.bind(document,show,3)(4)  //改this为document指向;

var a = { name:'hello' },b = { age:20 };
    var c = angular.copy(a)
    var d = angular.copy(a,b) //a把报有值给了b,相当于 b复制了a;
    console.log(d);


var a = { name:'hello' },b = { age:20 };
    var c = angular.extend(a,b)  //相当于把a 、b 都给了a
    console.log(a);  //所以此时 c == a;

angularJs的工具方法

angular.isArray
angular.isDate
angular.isDefined
angular.isUndefined
angular.isFunction
angular.isNumber
angular.isObject
angular.isString
angular.isElement
angular.version
angular.equals
angular.forEach
angular.fromJson/toJson
angular.identity/noop:传什么输出即什么/空函数
angular.lowercase/uppercase :大小写
angular.element:获取元素,相当于$
angular.bootstrap:初始化的一种方式 动态初始化代替ng-app
angular.injector:注册器,主要在内部使用,外部较少使用
function noop(){} //空函数
//可能的作用如下:如果不传可能出问题;
function transformer(transformationFn,value){
    return (transformationFn || angular.identity(value)) ;
}

//不使用ng-app时
document.onclick = function () {
    var _div = document.getElementsByTagName('div')
    angular.bootstrap(_div[0],['myApp1'])
    angular.bootstrap(_div[1],['myApp2']) //分别初始化调用,(目标元素,加载模块)
  //angular.bootstrap(document,['myApp']) //初始化在document上, 想要触发时再触发发;
}

var _div = document.getElementById('div1')
angular.element(_div).css('background','red')

$scope

$scope.$watch
$scope.$apply

angular.module

controller
run
function Aaa($scope) { //不注入$timeout
    $scope.name = 'hello'
    setTimeout(function(){  //使用原生
        $scope.$apply(function () {  //可以监听函数下的数据是否变化,如果有变化就会影响到视图,可以在第三方的库或原生js直接使用;
            $scope.name = 123
        })
    },2000)
}



angularJs的过滤器

currency
number
lowercase/uppercase
json
limitTo
date
orderBy
filter

过滤器扩展部分

可组合使用过滤器
JS中使用过滤器
$scope/$rootScope/$timeout
$filter
    var m1 = angular.module('myApp',[]);  //模块的写法 模块的写法要带出参数
        m1.controller('Aaa',['$scope',function($scope){
            $scope.name = '456456456.0322021'
            $scope.name = 'heoow'
            $scope.name = {'name':'elmok','age':30}
            $scope.name = ['a','b','c']
            $scope.name ='1231235'
            $scope.name = [   //orderBy,针对下面这种形式,数组里json
                {color:'red',age:20},
                {color:'yeloo',age:22},
                {color:'yeloo',age:23},
                {color:'#f9f9f9',age:24}
            ]
        }])
<div ng-controller="Aaa"> 
    {{name | currency:"¥"}}
    {{name | number :2}} //number只加分隔符 有小数情况下只截取前3位 后面参数代表要保留几位小数点;
    {{name | uppercase}}
    <pre>{{name | json}}</pre> //格式化 注意,需要在pre标签里
    {{name | limitTo:2}}  //后面即代表需要截取几位
    {{ name | date:'yyyy-MM-dd HH:mm:ss Z'}}  //Jan 1, 1970
    {{name | orderBy:'age':true}}  //加true 相反排序 
    {{name |filter:'l'}}   //  针对数据中的value值  加true==整个value值匹配,不能字符匹配
    
</div>

自定义过滤器

angular.module
controller/run
filter
var m1 = angular.module('myApp',[]);

//模块对象下的方法filter调用; 创建首字母变大写的过滤器;
m1.filter('filterUppercase',function(){
    return function (str,num) {
        console.log(num); //2,可找到num了,所以可做下一步操作;
        console.log(str);//返回的是传入的
        return str.charAt(0).toUpperCase() + str.substring(1)
    }
})

//使用
m1.controller('Aaa',['$scope','$filter',function($scope,$filter){
/*
    $scope.name = '456456456.0322021'
    $scope.name = 'heoow'
    $scope.name = {'name':'elmok','age':30}
    $scope.name = ['a','b','c']
    $scope.name ='1231235'
    $scope.name = $filter('uppercase')('heoow') //转大写操作;
    $scope.name = $filter('number')('123456') //转大写操作;
    $scope.name = $filter('number')('123456.12312',1) //转大写操作; //后面为限制小数点个数
    $scope.name = $filter('date')('4512312123','hh') //转日期;
*/
    $scope.name = $filter('filterUppercase')('heoow','2')
}])

ng-repeat指令

遍历集合, 通过in的方式遍历每一项, $index :$index每一项返回index
$first :$first 第一项返回true,其它返回false
$middle: $middle,除非第一项与最后一项,其它返真
$last: $last 最后一项返回true,其它返回true;
$even :偶数行返回true,奇数行返回false
$odd :与上相反
ng-repeat-start : 只循环一个li
ng-repeat-end
var m1 = angular.module('myApp',[])
    m1.controller('Aaa',['$scope',function($scope){
        $scope.dataList = [
                'aaa','bbb','ccc'
        ]
    }])
 <li ng-repeat="d in dataList">{{d}}</li> <!-- d 循环中的每一项 -->

表格小例

var m1 = angular.module('myApp',[])
m1.controller('Aaa',['$scope','$filter',function($scope,$filter){
    var oriArr = [
        {name:'red',age:'29'},
        {name:'black',age:'22'},
        {name:'blue',age:'23'},
        {name:'yellow',age:'24'}
    ];;
    $scope.dataList =oriArr;
    $scope.fnSort = function (arg) {
        //函数挂属性:分别有开关,加属性;一次真一次假,
        arguments.callee['fnSort' + arg] = !arguments.callee['fnSort' + arg];
        $scope.dataList = $filter('orderBy')($scope.dataList, arg, arguments.callee['fnSort' + arg]);
        //排序完结果重新赋值
    }
    $scope.fnfilter = function (){
        $scope.dataList = $filter('filter')(oriArr,$scope.filterVal)
    }
}])
<div ng-controller="Aaa">
    <input type="text" name="" id="" ng-model="filterVal"/> <input type="button" value="Search" ng-click="fnfilter()"/>
    <table border="1">
        <tr>
            <th ng-click="fnSort('name')">姓名</th>
            <th ng-click="fnSort('age')">年龄</th>
        </tr>
        <tr ng-repeat="d in dataList">
            <td>{{d.name}}</td>
            <td>{{d.age}}</td>
        </tr>
    </table>
</div>

隔行变色等;

var m1 = angular.module('myApp',[])
m1.controller('Aaa',['$scope',function($scope){
    $scope.dataList = [
        'aaa','bbb','ccc','ddd','eee','ggg'
    ]
}])
<div ng-controller="Aaa">
    <ul>
    <li ng-repeat="d in dataList">{{$index}}</li> <!-- d 循环中的每一项 -->   $index每一项返回index        
        <li class="{{$even ? 'active' : ''}}" ng-repeat="d in dataList">{{$odd}}</li>
        <li class="{{$even ? 'active' : ''}}" ng-repeat="d in dataList">{{d}}</li>
    </ul>
    
    <!--需求,下面的循环,不改变结构-->
    <div ng-repeat-start="d in dataList">{{d}}</div>
    <p>{{d}}</p>
    <div ng-repeat-end>{{d}}</div>
</div>

事件指令

ng-click/dblclick
ng-mousedown/up
ng-mouseenter/leave
ng-mousemove/over/out
ng-keydown/up/press
ng-focus/blur
ng-submit
ng-selected
ng-change
ng-copy
ng-cut
ng-paste
ng-disabled
服务 $interval
ng-readonly
ng-checked
ng-value
ng-bind
ng-cloak
ng-bind-template
ng-bind-html
http://www.bootcdn.cn/angular.js/
ng-non-bindable
var m1  = angular.module('myApp',[]);
m1.controller('Aaa',['$scope',function($scope){
    $scope.name = 'hwoow'
}])
<div ng-controller="Aaa">
    <input type="checkbox" name="" id="" ng-model="aaa"/> <!-- 点击则aaa改为true,所以选中 -->
    <select name="" id="">
        <option value="1">111</option>
        <option value="2" ng-selected="aaa">222</option>

    </select>
    <input type="text" name="" id="" ng-change="bbb='heoo" ng-model="bbb"/>{{bbb}}
    <!--ng-change必须与ng-model相配合才有用-->
    <br/>
    <input type="text" name="" id="" value="sdaflskldfj" ng-copy="ccc='dd'"/>{{ccc}}  <!-- 复制会输出 -->
    <input type="text" name="" id="" value="sdaflskldfj" ng-cut="ccc=true"/>{{ccc}}  <!-- 剪切会输出 -->

    <input type="text" name="" id="" value="sdaflskldfj" ng-paste="ccc=true"/>{{ccc}}

</div>
var m1 = angular.module('myApp', [])
m1.controller('Aaa', ['$scope', '$interval', function ($scope, $interval) {
    var inow = 5;
    $scope.text = inow + 's'
    $scope.isDisabled = true;
    var _t = $interval(function () {
        $scope.text = inow + 's'
        inow--
        if (inow == 0) {
            $interval.cancel(_t)   //清除定时器;
            $scope.text = '可以点击啦'
            $scope.isDisabled = false;
        }
    }, 1000)
}])
<div ng-controller="Aaa">
    <input type="button" value="{{text}}" ng-disabled="isDisabled"/> <!-- 动态修改按钮的状态; -->
    <input type="text" value="{{text}}" ng-readonly="isDisabled"/>
    <input type="checkbox" value="{{text}}" name="" id="" ng-checked="isDisabled"/>     <!-- 选中与不选 中; -->

    <input type="text" ng-value="text"/> <!-- 加上ng后value ,不需要{}  区别不大,推荐所有使用ng-value 提高用户体验 -->
</div>
var m1 = angular.module('myApp',['ngSanitize']) /* 操作html需要下载:angular-sanitize.js */ 
m1.controller('Aaa',['$scope',function($scope){
    alert(123)
    $scope.text = '<h1>hello</h1>'
}])
<div>{{text}},{{text}}</div>
//换个写法;
<div ng-bind-template="{{text}},{{text}}"></div>
<div ng-cloak>{{text}}</div> <!--  相当于未解析完时标签是display:none;,解析完再显示;-->
<div ng-non-bindable="">{{text}}</div>  <!-- 不想被解析时; -->

css操作

* ng-class
* ng-style
* ng-href
* ng-src
* ng-attr-(suffix) //通用写法;
var m1 = angular.module('myApp',[]) /* 操作html */
m1.controller('Aaa',['$scope',function($scope){
    $scope.text = '<h1>hello</h1>';
    $scope.style = "{color:'red',background:'#f3f3f3}'"
    $scope.sClass={red:true,yellow:true}
    $scope.url="http://www.baidu.com"
}])
var m2 = angular.module('myApp2',[])
m2.controller = ('Bbb',['$scope',function($scope){
}])
<div ng-controller="Aaa">
    <div ng-class="{red:true,color:true}">{{text}}</div>
    <div ng-class="{{sClass}}">{{text}}</div><!-- 注意此处需要加{{}} -->
    <div ng-style="{color:'red',background:'#f3f3f3'}">{{text}}</div>
    <div ng-style="{{style}}">{{text}}</div> <!-- 注意此处需要加{{}} -->
    <a ng-href="{{url}}">aaa</a>
    <a ng-attr-href="{{url}}" ng-attr-title="{{text}}">aaa</a>
</div>

dom操作

ng-show
ng-hide :ng-show与ng-hide:对display操作;
ng-if
ng-swtich :有选择性进行切换; 不需要属性 ,了解即可;
on
default
when
ng-open :ng-open; ff不支持;
var m1 = angular.module('myApp',[]) /* 操作html */
m1.controller('Aaa',['$scope',function($scope){
        $scope.btn = true;
}])
<input type="checkbox" name="" id="" ng-model="btn"/> 
<div ng-switch on="btn"><p ng-switch-default>默认是的</p><p ng-switch-when="false">切换隐藏的</p></div>

未完

Less 語言特性

http://less.bootcss.com/features/#mixins-parametric-feature
<h3>變量</h3>

@nice-blue: #5B83AD;
@light-blue: @nice-blue + #111;

#header {
  color: @light-blue;
}

/*輸出*/
#header {
  color: #6c94be;
}

注意,由于变量只能定义一次,其本质就是“常量”。



<h3>混合(Mixin)</h3>

相當於“繼承”

.bordered {
  border-top: dotted 1px black;
  border-bottom: solid 2px black;
}
#menu a {
  color: #111;
  .bordered;
}

/*輸出*/
#menu a {
  color: #111;
  border-top: dotted 1px black;
  border-bottom: solid 2px black;
}

class與id同樣適用,當mixin時,()是可選的

.a, #b {
  color: red;
}

.mixin-id {
  #b();
}

/*輸出*/
.mixin-id {
  color: red;
}

<h3>嵌套规则</h3>

header{
  color: #cccccc;
  .nav{
    font-size: 12px;
  }
  .logo{
    width: 300px;
    .img{
      width: 100%;
    }
  }
}

/*輸出*/
header {
  color: #cccccc;
}
header .nav {
  font-size: 12px;
}
header .logo {
  width: 300px;
}
header .logo .img {
  width: 100%;
}

&代表父級

.clearfix {
  display: block;
  zoom: 1;
  &:after {
    content: " ";
    display: block;
    font-size: 0;
    height: 0;
    clear: both;
    visibility: hidden;
  }
}

/*輸出*/
.clearfix {
  display: block;
  zoom: 1;
}
.clearfix:after {
  content: " ";
  display: block;
  font-size: 0;
  height: 0;
  clear: both;
  visibility: hidden;
}

a {
  color: blue;
  &:hover {
    color: green;
  }
}

/*輸出*/
a {
  color: blue;
}
a:hover {
  color: green;
}

&-生產名

.button{
  &-ok{
    background: #000;
  }
}

/*輸出*/
.button-ok {
  background: #000;
}

&組合

.c{
  &+&{
    color: red;
  }
  &&{
    color:blue;
  }
  & & {
    color:yellow
  }
  &,&con{
      color:pink
  }
}

/*輸出*/
.c + .c {
  color: red;
}
.c.c {
  color: blue;
}
.c .c {
  color: yellow;
}
.c, .ccon {
  color: pink;
}

&同時代表的所有長輩元素,不僅僅是父級,所以多層選擇更簡潔:

.nav{
  .header{
    .logo{
      & input[type=text],& input[type=button]{
        color: green;
      }
    }
  }
}

/*輸出*/
.nav .header .logo input[type=text],
.nav .header .logo input[type=button] {
  color: green;
}

通過&改變選擇器父子關係 :

.h{
  .a{
    width:10px;
    .c{
      height:20px;
    }
  }
}
/*輸出*/
.h .a .c {
  height: 20px;
}

.h{
  .a{
    width:10px;
    .c &{    /*使.c成為父級*/
      height:20px;
    }
  }
}
/*輸出*/
.c .h .a {
  height: 20px;
}

生成可能排列的組合

p,a,ul,li{
  width: 10px;
  & &{
    height:0
  }
}

/*輸出*/
p,
a,
ul,
li {
  width: 10px;
}
p p,
p a,
p ul,
p li,
a p,
a a,
a ul,
a li,
ul p,
ul a,
ul ul,
ul li,
li p,
li a,
li ul,
li li {
  height: 0;
}

<h3>运算</h3>
任何数字、颜色或者变量都可以参与运算。下面是一组案例

@base: 5%;
@filler: @base * 2;
@other: @base + @filler;

div{
  color: #888 / 4;
  width:@base * 10;
  height: 100% / 2 + @filler;
}

/*輸出*/
div {
  color: #222222;
  width: 50%;
  height: 60%;
}

<h3>函数</h3>
http://baike.renwuyi.com/2015-04/9042.html

@base: #f04615;
@width: 0.5;

.class {
  width: percentage(@width); // 0.5轉50%
  color: saturate(@base, 5%); //顏色飽和度+5%
  background-color: spin(lighten(@base, 25%), 8); //顏色亮度+25%,色相+8
}


/*輸出*/
.class {
  width: 50%;
  color: #f6430f;
  background-color: #f8b38d;
}

<h3>命名空間規則</h3>

#logo {
  .img {
    width: 10px;
    height: 10px;
    &:hover {
      background-color: white
    }
  }
}
#nav a {
  color: orange;
  #logo > .img;
}

/*輸出*/
#logo .img {
  width: 10px;
  height: 10px;
}
#logo .img:hover {
  background-color: white;
}
#nav a {
  color: orange;
  width: 10px;
  height: 10px;
}
#nav a:hover {    //注意這一步也帶出
  background-color: white;
}

<h3>變量定義範圍</h3>
先找子範圍,不分前面,找不到再找父;所以下面兩種形式都只會找子範圍內的變量;

@var: red;

#page {
  @var: white;
  #header {
    color: @var; // white
  }
}
#page {
  #header {
    color: @var; // white
  }
  @var: white;
}

<h3>导入(Importe)</h3>
和你预期的工作方式一样。你可以导入一个 .less 文件,此文件中的所有变量就可以全部使用了。如果导入的文件是 .less 扩展名,则可以将扩展名省略掉:

@import "library"; // library.less
@import "typo.css";

<h3>變量替換</h3>

// Variables
@mySelector: banner;

// Usage
.@{mySelector} {
  font-weight: bold;
  line-height: 40px;
  margin: 0 auto;
}
// Variables
@images: "../img";
// 用法
body {
  color: #444;
  background: url("@{images}/white-sand.png");
}

注意:導入css或inport文件,此種變量定義不再適用;

// Variables 無法輸出
@themes: "../../src/themes";
// Usage
@import "@{themes}/tidal-wave.less";

属性

@property: color;

.widget {
  @{property}: #0ee;
  background-@{property}: #999;
}
@fnord:  "I am fnord.";
@var:    "fnord";
p{
  content: @@var;
}

可以後聲明

.lazy-eval {
  width: @var;
}
@var: @a;
@a: 9%;

同名變量遵循後蓋前,從裏到外原則

@var: 0;
.class1 {
  @var: 1;
  .class {
    @var: 2;
    three: @var;
    @var: 3;
  }
  one: @var;
}

/*輸出*/
.class1 {
  one: 1;
}
.class1 .class {
  three: 3;
}


<h3>Extend 擴展</h3>

nav ul {   //原樣式保持不變
  &:extend(.inline);         //與.inline生成擴展
  background: blue;
}
.inline {
  color: red;
}

/*輸出*/
nav ul {
  background: blue;
}
.inline, nav ul {
  color: red;
}

/*另一種寫法:*/

nav ul:extend(.inline){
  background: blue;
}

/*如果定義兩個空置屬性*/
.e:extend(.f) {}
.e:extend(.g) {}
==》
.e:extend(.f,.g){}

多個擴展只擴展對應的本位元素

.big-division,
.big-bag:extend(.bag),
.big-bucket:extend(.bucket) {
  background: #000;
}

/*如果.bag等存在,則輸出*/

.bag,
.big-bag {
  width: 100%;
}
.bucket,
.big-bucket {
  width: 55px;
}
.bucketone{
  tr{
    color:#cd000c;
  }
}
.some-class:extend(.bucketone tr){
}

/*輸出*/
.bucketone tr,.some-class {
  color: #cd000c;
}

如果extend是引用的屬性,則無法匹配

.a.class,.class.a,.class > .a ,*.class{
  color: blue;
}
.test:extend(.class) {} // 上面的.class都是被引用,所以這句無法匹配,(只有純寫.class{..才能匹配.})

順序不同也無法匹配

link:hover:visited {
  color: blue;
}
.selector:extend(link:visited:hover) {}

nth系也無法匹配

:nth-child(1n+3) {
  color: blue;
}
.child:extend(n+3) {}

引用不重要,以下是相同的

[title=identifier] {
  color: blue;
}
[title='identifier'] {
  color: blue;
}
[title="identifier"] {
  color: blue;
}

Extend的 all,以下replacement將會複製一份與.test同樣結構的屬性

.a.b.test, .test.c {
  color: orange;
}
.test {
  &:hover {
    color: green;
  }
}
.replacement:extend(.test all) {}

/*輸出*/
.a.b.test, .test.c, .a.b.replacement, .replacement.c {
  color: orange;
}
.test:hover, .replacement:hover {
  color: green;
}

變量生產出的屬性不能被匹配到extend

@variable: .bucket;
@{variable} { // interpolated selector
  color: blue;
}
.some-class:extend(.bucket) {} // does nothing, no match is found

變量與extend也不能匹配

.bucket {
  color: blue;
}
.some-class:extend(@{variable}) {} // interpolated selector matches nothing
@variable: .bucket;

//當然,這麼寫是無任何問題的
.bucket {
  color: blue;
}
@{variable}:extend(.bucket) {}
@variable: .selector;

//輸出:
.bucket,.selector {
  color: blue;
}

@media


1、比如:print裏的@media只會匹配print裏面的

2、寫在@media內部的extend無法繼承子塊的樣式

@media screen {
  .screenClass:extend(.selector) {} // extend inside media
  @media (min-width: 1023px) {
    .selector {  // ruleset inside nested media - extend ignores it
      color: blue;
    }
  }
}

/*輸出*/
@media screen and (min-width: 1023px) {
  .selector {
    color: blue;
  }
}
很明顯:.screenClass:extend(.selector) {}不會被匹配到;

3、extend寫在@media外部可匹配到內部所有選擇器樣式

@media screen {
  .selector {
    color: blue;
  }
  @media (min-width: 1023px) {
    .selector {
      color: blue;
    }
  }
}
.topLevel:extend(.selector) {}

/*輸出*/
@media screen {
  .selector,
  .topLevel {
    color: blue;
  }
}
@media screen and (min-width: 1023px) {
  .selector,
  .topLevel {
    color: blue;
  }
}



<h3>小例</h3>

/*定义base类*/
@def-bg:#f1f1f1;
@def-col:#464646;

.def-bg{
  background: @def-bg;
  color:@def-col;
}

//子类只改变颜色
.con-bg{
  &:extend(.def-bg);
  background: #cccccc;
}

/*输出*/
.def-bg,
.con-bg {
  background: #f1f1f1;
  color: #464646;
}
.con-bg {
  color: #cccccc;
}
<div class='def-bg con-bg'></div>

使用扩展减少CSS代码

.a(){
  width: 10px;
}
.b{
  .a;
}
.c{
  .a;
}

/*输出*/
.b {
  width: 10px;
}
.c {
  width: 10px;
}

/*使用extend*/
.a{
  width: 10px;
}
.b{
  &:extend(.a);
}
.c{
  &:extend(.a);
}

/*输出*/
.a,
.b,
.c {
  width: 10px;
}
li.list > a {
  width: 10px;
}
button.list-style {
  &:extend(li.list > a); // use the same list styles
}

li.list > a,
button.list-style {
  width: 10px;
}