如何在页脚追加Angular样式
要用angularJS为页脚或任何HTML元素添加CSS样式,如果我们有预定义的CSS类,我们可以使用ng-class指令,如果我们想在运行时动态地创建样式,则可以使用ng-style指令。
语法:
<footer ng-style="jsObject">...</footer>
或者,
<footer ng-class="jsObject/Array/String">...</footer>
在ng-style指令中,jsObject包含了CSS的键值对。
在ng-class指令中,表达式可以是一个jsObject、数组或字符串。这里的jsObject是一个CSS类名称和一个布尔值的键值对映射,String只是CSS类的名称,而Array可以是两者。
例子1:在这个例子中,我们使用ng-style指令将样式附加到页脚元素。
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<script src=
"https://ajax.googleapis.com/ajax/libs/angularjs/1.7.8/angular.min.js">
</script>
</head>
<body ng-controller="MyController">
<button type="button"
ng-click="click(this)">GFG
</button>
<!-- ng-style to append styles on footer -->
<footer ng-style="styleObj">
<hr>
<h1>GeeksForGeeks!</h1>
</footer>
<script type="text/javascript">
var myApp = angular.module('myApp', []);
myApp.controller('MyController', [
'scope', function(scope) {
scope.styleObj = {
"color": "green"
}
scope.click = function(scope) {
// CSS key value pairs to append new
// style of background-color
scope.styleObj["background-color"] = "green";
// Modifying existing style
$scope.styleObj["color"] = "black";
}
}
]);
</script>
</body>
</html>
输出:
- 在点击按钮之前。
- 点击该按钮后。
当我们按下按钮GFG时,它将调用点击函数。然后,点击函数通过给styleObj一个新的属性并修改现有的属性来改变它的值。
例子2:在这个例子中,我们使用ng-class指令和一个对象来给页脚元素添加样式。
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<style>
.gfg {
background-color: green;
}
</style>
<script src=
"https://ajax.googleapis.com/ajax/libs/angularjs/1.7.8/angular.min.js">
</script>
</head>
<body ng-controller="MyController">
<button type="button" ng-click="click(this)">
GFG
</button>
<footer ng-class="clsObj">
<hr>
<h1>GeeksForGeeks!</h1>
</footer>
<script type="text/javascript">
var myApp = angular.module('myApp', []);
myApp.controller('MyController', [
'scope', function(scope) {
scope.clsObj = {
"gfg": false
}
scope.click = function(scope) {
scope.clsObj["gfg"] = true;
}
}
]);
</script>
</body>
</html>
输出:
- 在按下按钮之前。
- 按下按钮后。