当前位置:   article > 正文

AngularJS ng-class、ng-style

ng-style
一、 ng-class

ng-class 指令用于给 HTML 元素动态绑定一个或多个 CSS 类。

ng-class 指令的值可以是字符串,对象,或一个数组。

  • 如果是字符串,多个类名使用空格分隔。
  • 如果是对象,需要使用 key-value 对,key 为你想要添加的类名,value 是一个布尔值。只有在 value 为 true 时类才会被添加。
  • 如果是数组,可以由字符串或对象组合组成,数组的元素可以是字符串或对象。

1.1 示列

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="https://cdn.staticfile.org/angular.js/1.4.6/angular.min.js"></script>
<style>
.sky {
    color:white;
    background-color:lightblue;
    padding:20px;
    font-family:"Courier New";
}
.tomato {
    background-color:coral;
    padding:40px;
    font-family:Verdana;
}
</style>
</head>
<body ng-app="">

<p>选择一个类:</p>

<select ng-model="home">
<option value="sky">天空色</option>
<option value="tomato">番茄色</option>
</select>

<div ng-class="home">
  <h1>Welcome Home!</h1>
  <p>I like it!</p>
</div>

</body>
</html>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35

1.2 其他写法

// isCurrentPage是一个函数,当执行结果为true时设置class为class
ng-class="{className1: isCurrentPage(client), className2: classIsTrue(str)}

// 当值(key1、key2为true时设置指定的class1,class2)
ng-class="{class1: key1, class2: key2}

// 选定指定的class
ng-class="{'key1':'class1', 'key2':'class2'}['key2']"

// 指定多个class
ng-class="['className1','className2']"

// 三元表达式
ng-class="obj ? 'class1': 'class2'"
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
二、ng-style

ng-style 指令为 HTML 元素添加 style 属性。
ng-style 属性值必须是对象,表达式返回的也是对象。

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="https://cdn.staticfile.org/angular.js/1.4.6/angular.min.js"></script>
</head>
<body ng-app="myApp" ng-controller="myCtrl">

<h1 ng-style="myObj">显示效果</h1>

<script>
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
  $scope.myObj = {
    "color" : "white",
    "background-color" : "coral",
    "font-size" : "60px",
    "padding" : "50px"
  }
});
</script>

</body>
</html>

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/羊村懒王/article/detail/436126
推荐阅读
相关标签
  

闽ICP备14008679号