边框闪烁 - Anuglarjs

半兽人 发表于: 2024-05-16   最后更新时间: 2024-05-16 16:13:28  
{{totalSubscript}} 订阅, 207 游览

保存验证的时候,如果异常,希望触发闪烁效果。

可以使用 AngularJS 的指令和样式来实现这个功能。需要动态地添加和删除一个用于闪烁的 CSS 类。


<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>AngularJS Border Flash</title>
  <style>
    @keyframes borderFlash {
      0%, 100% {
        border-color: transparent;
      }
      12.5%, 37.5%, 62.5%, 87.5% {
        border-color: red; /* 你可以替换成任何你想要的颜色 */
      }
      25%, 50%, 75% {
        border-color: transparent;
      }
    }

    .flash-border {
      border: 2px solid transparent; /* 初始状态的边框 */
      animation: borderFlash 2s ease-in-out; /* 动画持续时间为2秒 */
    }
  </style>
</head>
<body ng-app="myApp" ng-controller="MainCtrl">
  <div ng-repeat="hostname in srcData.dataCache track by $index" class="mb-1 d-flex">
    <input ng-if="hostname.edit" type="text" class="form-control" ng-model="hostname.hostnames[$index]" ti-validation="validation.hostname" ti-text flash-on-edit="hostname.edit">
    <span ng-if="!hostname.edit">{{hostname.hostnames[$index]}}</span>
  </div>
  <button ng-click="triggerFlash()">点击我让边框闪烁</button>

  <script src="/user/js/angular-1.5.8.min.js"></script>

  <script>
    var app = angular.module('myApp', []);

    app.directive('flashOnEdit', ["$timeout", function ($timeout) {
      return {
        link: function (scope, element, attrs) {
          scope.$watch(attrs.flashOnEdit, function (newVal) {
            if (newVal) {
              element.addClass('flash-border');
              $timeout(function () {
                element.removeClass('flash-border');
              }, 2000); // 与动画持续时间一致
            }
          });
        }
      };
    }]);

    app.controller('MainCtrl', ['$scope', '$timeout', function($scope, $timeout) {
      $scope.srcData = {
        dataCache: [
          { edit: true, hostnames: ["host1"] },
          { edit: false, hostnames: ["host2"] }
        ]
      };

      $scope.triggerFlash = function() {
        angular.forEach($scope.srcData.dataCache, function(data) {
          if (data.edit) {
            data.edit = false;
            $timeout(function() {
              data.edit = true;
            }, 0); // 确保 edit 被重新设置为 true 以触发 $watch
          }
        });
      };
    }]);
  </script>
</body>
</html>

在线运行

css
更新于 2024-05-16

查看AngularJS更多相关的文章或提一个关于AngularJS的问题,也可以与我们一起分享文章