AngularJS中的ng-class指令用于指定HTML元素上的CSS类。它用于动态绑定HTML元素上的类。如果ng-class指令内的表达式返回true,则仅添加该类,否则不添加。所有HTML元素都支持它。
用法:
<element ng-class="expression"> Contents... </element>
范例1:本示例使用ng-class指令设置和重置CSS类。
<!DOCTYPE html>
<html>
<head>
<title>ng-class Directive</title>
<script src=
"https://ajax.googleapis.com/ajax/libs/angularjs/1.4.2/angular.min.js">
</script>
<style>
.edit {
color:green;
font-size:1.5em;
}
</style>
</head>
<body ng-app="" style="text-align:center">
<h1 style="color:green">GeeksforGeeks</h1>
<h2>ng-class Directive</h2>
<div>
<input type="button" ng-click="edit=true" value="Style" />
<input type="button" ng-click="edit=false" value="Reset" />
<br><br>
<span ng-class="{true:'edit'}[edit]">
GeeksforGeeks
</span>
is the computer science portal for geeks.
</div>
</body>
</html>
输出:
单击按钮之前:
单击样式按钮后:
范例2:本示例使用ng-class指令将CSS样式设置为该类。
<!DOCTYPE html>
<html>
<head>
<title>ng-class Directive</title>
<script src=
"https://ajax.googleapis.com/ajax/libs/angularjs/1.4.2/angular.min.js">
</script>
<style type="text/css">
.index {
color:white;
background-color:green;
}
</style>
</head>
<body ng-app="app" style="padding:20px">
<h1 style="color:green">GeeksforGeeks</h1>
<h2>ng-class Directive</h2>
<div ng-controller="geek">
<table>
<thead>
<th>Select any sorting technique:</th>
<tr ng-repeat="i in sort">
<td ng-class="{index:$index==row}"
ng-click="sel($index)">
{{i.name}}
</td>
</tr>
</thead>
</table>
</div>
<script>
var app = angular.module("app", []);
app.controller('geek', ['$scope', function ($scope) {
$scope.sort = [
{ name:"Merge sort" },
{ name:"Quick sort" },
{ name:"Bubble sort" }
];
$scope.sel = function (index) {
$scope.row = index;
};
}]);
</script>
</body>
</html>
输出:
选择元素之前:
选择元素后:
相关用法
- AngularJS ng-if用法及代码示例
- AngularJS ng-cut用法及代码示例
- AngularJS ng-value用法及代码示例
- AngularJS ng-src用法及代码示例
- AngularJS ng-app用法及代码示例
- AngularJS ng-csp用法及代码示例
- AngularJS ng-jq用法及代码示例
- AngularJS ng-required用法及代码示例
- AngularJS ng-bind用法及代码示例
- AngularJS ng-srcset用法及代码示例
- AngularJS ng-paste用法及代码示例
- AngularJS ng-submit用法及代码示例
- AngularJS ng-style用法及代码示例
- AngularJS ng-selected用法及代码示例
注:本文由纯净天空筛选整理自Vishal Chaudhary 2大神的英文原创作品 AngularJS | ng-class Directive。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。