angularjs ng-class

本文详细介绍了 AngularJS 中 ngClass 指令的三种使用方式:字符串、数组及对象形式,并通过实例展示了如何根据不同条件动态改变 HTML 元素的 CSS 类。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

api

https://docs.angularjs.org/api/ng/directive/ngClass
http://docs.ngnice.com/api/ng/directive/ngClass

使用方式

The directive operates in three different ways, depending on which of three types the expression evaluates to:

1,If the expression evaluates to a string, the string should be one or more space-delimited class names.
2,If the expression evaluates to an array, each element of the array should be a string that is one or more space-delimited class names.
3,If the expression evaluates to an object, then for each key-value pair of the object with a truthy value the corresponding key is used as a class name.

三种使用方式,分别通过三种类型的(表达式计算出的)值

方式1: 当值为一个字符串时,它就会把用空格分开的字符串加到class中

方式2: 当值为一个数组时,它的每个字符串元素都会被加到class中

方式3: 当值为一个对象时(key=>value),把value为true的key加到class中

常用实例

官网三种,分别对应键值对对象,字符串,字符串数组

<p ng-class="{strike: deleted, bold: important, red: error}">Map Syntax Example</p>
<input type="checkbox" ng-model="deleted"> deleted (apply "strike" class)<br>
<input type="checkbox" ng-model="important"> important (apply "bold" class)<br>
<input type="checkbox" ng-model="error"> error (apply "red" class)
<hr>
<p ng-class="style">Using String Syntax</p>
<input type="text" ng-model="style" placeholder="Type: bold strike red">
<hr>
<p ng-class="[style1, style2, style3]">Using Array Syntax</p>
<input ng-model="style1" placeholder="Type: bold, strike or red"><br>
<input ng-model="style2" placeholder="Type: bold, strike or red"><br>
<input ng-model="style3" placeholder="Type: bold, strike or red"><br>
.strike {
  text-decoration: line-through;
}
.bold {
    font-weight: bold;
}
.red {
    color: red;
}

另外一个键值对常用实例

<p ng-class="{true:'red', false :'green'}[color]">Map Syntax Example 2</p>
  <input type="checkbox" ng-model="color"> red <br>

动画

<input id="setbtn" type="button" value="set" ng-click="myVar='my-class'">
<input id="clearbtn" type="button" value="clear" ng-click="myVar=''">
<br>
<span class="base-class" ng-class="myVar">Sample Text</span>
.base-class {
  -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
}

.base-class.my-class {
  color: red;
  font-size:3em;
}

demo

http://download.youkuaiyun.com/detail/superjunjin/9733678

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值