一尘不染

AngularJs切换ng-class ng-click

angularjs

任何人都可以为该JSFiddle提供正确的方法:

<style>
 .red #btn{
     background-color:red;
  }

 .blue #btn{
    background-color:blue;
  }
 </style>

 <body ng-app="ap" ng-controller="con">
    <button id="btn" ng-click="changeClass()">Change Class</button>    
 </body>

 <script>
  var app = angular.module("ap",[]);

  app.controller("con",function($scope){

  $scope.class = "red";

  $scope.changeClass = function(){
     if ($scope.class === "red #btn")
         $scope.class = "blue #btn";
      else
         $scope.class = "red #btn";
   };
 });

 </script>

JsFiddle链接

我正在尝试通过.class&#ID更改元素的类。

提前致谢

感谢tymeJV,新的JSFiddle:


阅读 160

收藏
2020-07-04

共1个答案

一尘不染

正确的方法是ng-class根据切换变量使用,请考虑:

CSS:

.red {
    color: red;
}

JS:

$scope.toggle = false;

HTML:

<button id="btn" ng-click="toggle = !toggle" ng-class="{'red' : toggle}">Change Class</button>

ng-class通过根据变量(“ toggle”)是否为true或分配引用的类(在上面为“红色”)来工作false

2020-07-04