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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。