You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

AngularJS实现依次滑下显示消息遇问题:仅显示最后一条

AngularJS滑下提示框仅显示最后一条消息的问题

我尝试使用AngularJS实现滑下式提示框,以下是我的代码:

控制器代码

function LoginController($scope, $timeout) {
  $scope.alerts = [{
      name: "Alert 01 something something"
    },
    {
      name: "Alert 02 something something"
    }
  ];

  $scope.currentAlert = {
    name: "Something something"
  };

  $scope.showFeedback = function() {
    $("#notification-alert").slideDown(500);
    $timeout(() => {
      $("#notification-alert").slideUp();
    }, 1500)
  };

  $scope.goThroughAlert();
}

HTML代码

<div ng-app ng-controller="LoginController">
     <div class="alert alert-info my-feedback" id="notification-alert">
        <div>{{currentAlert.name}}</div>
    </div>
</div>

我编写了goThroughAlert方法,希望遍历alerts数组并依次滑下显示每条消息:

$scope.goThroughAlert = function() {
  for (i = 0, length = $scope.alerts.length; i < length; i++) {
    let current = $scope.alerts[i];
    $scope.currentAlert.name = current.name;
    $scope.showFeedback();
  }
}

但目前仅能显示Alert 02,需要实现先显示Alert 01,待其滑上后再显示Alert 02,数组有更多元素则依次类推。


错误原因

  1. 同步循环覆盖值:for循环是同步执行的,会在瞬间遍历完所有数组元素,直接将currentAlert.name设置为最后一条消息的内容,前面的赋值操作被立即覆盖。
  2. 异步动画冲突:showFeedback中的slideDown和$timeout都是异步操作,循环执行时所有动画几乎同时触发,最终只会呈现最后一条消息的动画效果。

解决方案

使用递归函数实现顺序执行,等待上一条消息的动画完全结束后,再处理下一条:

修改后的goThroughAlert方法

$scope.goThroughAlert = function(index = 0) {
  // 遍历完成时终止递归
  if (index >= $scope.alerts.length) return;
  
  let current = $scope.alerts[index];
  $scope.currentAlert.name = current.name;
  
  // 按顺序执行动画:滑下 -> 等待 -> 滑上 -> 处理下一条
  $("#notification-alert").slideDown(500, () => {
    $timeout(() => {
      $("#notification-alert").slideUp(500, () => {
        // 滑上动画完成后,递归处理下一条消息
        $scope.goThroughAlert(index + 1);
      });
    }, 1500);
  });
};

补充CSS样式

确保提示框初始状态为隐藏,才能触发slideDown效果:

.my-feedback {
  display: none;
}

内容的提问来源于stack exchange,提问作者loveprogramming

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 19:05:56