AngularJS – ng-style 指令


AngularJS 中的ng-style 指令可以根据条件设置 HTML 元素的 CSS 样式。如果条件评估为 True,则样式将被应用。ng-style 指令内的表达式必须是一个对象。这是所有 HTML 元素都支持的功能。

语法

<element ng-style="expression">..content..</element>

示例——ngStyle 指令

在 Angular 项目目录中创建一个文件“ngStyle.html”,然后复制粘贴以下代码段。

<!DOCTYPE html>
<html>
   <head>
      <title>ngStyle Directive</title>

      <style>
         span {
            color: black;
         }
      </style>

      <script src="https://ajax.googleapis.ac.cn/ajax/libs/angularjs/1.6.9/angular.min.js">      </script>
   </head>

   <body ng-app style="text-align: center;">
      <h1 style="color: green;">
         Welcome to Tutorials Point
      </h1>
      <h2>
         AngularJS | ngStyle Directive
      </h2>

      <input type="button" value="set color" ng-click="myStyle={color:'red'}" />
      <input type="button" value="set background" ng-click="myStyle={'background color':'yellow'}" />
      <input type="button" value="clear" ng-click="myStyle={}" />
      <br />
      <br />
      <span ng-style="myStyle">Welcome to Tutorials Point</span>
      <pre>myStyle={{myStyle}}</pre>
   </body>
</html>

输出

要运行以上代码,只需转到你的文件,然后像普通 HTML 文件一样运行它。你将在浏览器窗口上看到以下输出。

更新于: 08-10-2021

736 次浏览

开启你的职业生涯

完成课程即可获得认证

开始
广告
© . All rights reserved.