css - 使用 ng-click 存储和调用类

标签 css angularjs

我已经实现了一个 ng-click切换 <div>两个 css 类之间的标签。本例中的“开”和“关”

默认使用'off' 类。

我觉得我应该使用一个 bool 值来跟踪它是否被点击(真/假),但不确定如何或在哪里实现它。或者有更短的方法吗?

var app = angular.module("myApp", []);

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

  $scope.class = "off";

  $scope.changeClass = function() {
    if ($scope.class === "off")
      $scope.class = "on";
    else
      $scope.class = "off"
  };

});
.off {
  border: 1px solid black;
  background-color: white;
  box-sizing: border-box !important;
  border-radius: 200px !important;
  font: 30px 'Roboto';
  font-weight: 400;
  padding: 10px, 10px, 10px, 10px;
  color: black;
  text-align: center;
  width: 80px;
  height: 80px;
  display: inline-block;
  float: left;
  overflow: hidden;
  line-height: 80px;
}

.on {
  border: 1px solid black;
  background-color: blue;
  box-sizing: border-box !important;
  border-radius: 200px !important;
  font: 30px 'Roboto';
  font-weight: 400;
  padding: 10px, 10px, 10px, 10px;
  color: black;
  text-align: center;
  width: 80px;
  height: 80px;
  display: inline-block;
  float: left;
  overflow: hidden;
  line-height: 80px;
}

.circle:hover {
  font-weight: 400;
  background: #9fa8da;
  color: #f7f3eb;
  z-index: 9999;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.8/angular.min.js"></script>
<div ng-app="myApp" ng-controller="clickToggle">

  <div class="circle" ng-class="class" ng-click="changeClass()">1</div>

</div>

最佳答案

如果默认使用 .off 类,那么您可以将默认样式应用于 .circle。 此后,您只需单击即可打开和关闭 .on

angular.module("myApp", [])
.controller("clickToggle",['$scope', function($scope) {
  $scope.changeClass = function() {
    $scope.isActive = !$scope.isActive;
  };
}]);
.circle {
  border: 1px solid black;
  background-color: white;
  box-sizing: border-box !important;
  border-radius: 200px !important;
  font: 30px 'Roboto';
  font-weight: 400;
  padding: 10px, 10px, 10px, 10px;
  color: black;
  text-align: center;
  width: 80px;
  height: 80px;
  display: inline-block;
  float: left;
  overflow: hidden;
  line-height: 80px;
}

.on {
  background-color: blue;
}

.circle:hover {
  background: #9fa8da;
  color: #f7f3eb;
  z-index: 9999;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.8/angular.min.js"></script>
<div ng-app="myApp" ng-controller="clickToggle">

  <div class="circle" ng-class="{'on': isActive}" ng-click="changeClass()">1</div>

</div>

关于css - 使用 ng-click 存储和调用类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56009770/

相关文章:

出现滚动条时,css 伪元素(tr 外的三 Angular 形)位置未对齐

php - 如何编辑 htaccess 文件

javascript - 离线时浏览器是否加载缓存图像?

angularjs - 在 AngularJS 的 ng-bind 中使用过滤器后添加更多文本

html - 外部 CSS !important 覆盖内联 !important

javascript - 如何在angularjs中将base64编码的数据解码为ascii

javascript - 使用angularjs在特定页面加载外部库

css - 是否可以通过 Hostbinding 访问 css class::after 和::before 选择器?

html - select2 所需的选择器

html - 在一个 div 中重叠 div