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

如何实现滚动至div底部时触发alert弹窗?

实现AngularJS中滚动到Div底部触发Alert弹窗

嘿,这需求其实很好实现,咱们基于你提供的代码调整优化下,就能稳定达成效果:

核心思路

给目标.test元素绑定scroll事件,在事件回调里通过三个关键属性判断滚动位置:

  • scrollTop:元素已滚动的垂直距离
  • offsetHeight:元素的可见区域高度
  • scrollHeight:元素内容的总高度(包括不可见的滚动部分)
    当scrollTop + offsetHeight >= scrollHeight时,就说明滚动到了底部,触发alert即可。

完整可运行代码示例

HTML代码

<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.9/angular.js"></script>
<body ng-app="test" ng-controller="MyCtrl">
  <div class="test">
    Photography is the science, art, application and practice of creating durable images by recording light or other electromagnetic radiation, either electronically by means of an image sensor, or chemically by means of a light-sensitive material such as photographic film.[1] Typically, a lens is used to focus the light reflected or emitted from objects into a real image on the light-sensitive surface inside a camera during a timed exposure. With an electronic image sensor, this produces an electrical charge at each pixel, which is electronically processed and stored in a digital image file for subsequent display or processing. The result with photographic emulsion is an invisible latent image, which is later chemically "developed" into a visible image, either negative or positive depending on the purpose of the photographic material and the method of processing. A negative image on film is traditionally used to photographically create a positive image on a paper base, known as a print, either by using an enlarger or by contact printing. Photography is employed in many fields of science, manufacturing (e.g., photolithography), and business, as well as its more direct uses for art, film and video production, recreational purposes, hobby, and mass communication
  </div>
</body>

CSS代码

.test{
  overflow-y: scroll;
  height:100px;
  background: yellow;
}

AngularJS控制器代码

var app = angular.module('test', []);
app.controller('MyCtrl', function($scope) {
  // 用angular.element原生选择器更贴合AngularJS的写法
  angular.element('.test').bind('scroll', function(){
    console.log(`滚动状态:scrollTop=${this.scrollTop},可见高度=${this.offsetHeight},总高度=${this.scrollHeight}`);
    // 调整为>=判断,避免像素精度问题导致漏触发
    if (this.scrollTop + this.offsetHeight >= this.scrollHeight) {
      alert("已经滚动到底部啦!");
    }
  });
});

小细节优化说明

  1. 把document.querySelector('.test')替换为angular.element('.test'),更符合AngularJS的DOM操作规范;
  2. 将判断条件从>改为>=,因为部分场景下滚动到底部时,scrollTop + offsetHeight会刚好等于scrollHeight,用>=能确保触发逻辑不遗漏。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 07:34:55