AngularJS – ng-style 指令

angularjsweb developmentfront end technology更新于 2026/1/7 1:37:17

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.com/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 文件运行即可。您将在浏览器窗口中看到以下输出。


相关文章