gpt4 book ai didi

angularjs - 当用户滚动到 Angular js中的div顶部时如何显示警报?

转载 作者:行者123 更新时间:2023-12-04 17:47:02 24 4
gpt4 key购买 nike

您好,请问如何在 Angular js 中滚动到 div 顶部时显示警报,以及当用户滚动到底部时如何显示警报。实际上我知道如何在 jquery 中使用 if(this.scrollTop===0) 来实现这一点。但我是使用带有 Angular js的 ionic 框架。所以你能告诉我当用户滚动到顶部并显示警报时如何获取事件吗?

这是我的笨蛋
http://plnkr.co/edit/8bqDi69oiBKTpDvCaOf6?p=preview

<body ng-controller="MyController">
<div style="width:90%;height:150px;border:1px solid red;overflow:auto;overflow-y: scroll">
<div ng-repeat="n in name">{{n.name}}</div>
</div>

最佳答案

Angular 不会为此提供任何东西,你只需要在你的元素上绑定(bind)一个滚动事件。
在我当前的项目中,我刚刚在我的 Controller 中创建了一个事件:

var container = angular.element(document);
container.on('scroll', function() {
if (container.scrollTop() > 1000) {
$('#scroll-top-button').addClass('show');
} else {
$('#scroll-top-button').removeClass('show');
}
});
// in your case angular.element(document) should be your div instead of document

它确实表现得非常好(我希望滚动事件上的 if 会花费一些资源,但实际上并非如此)。

Angular 指令

简单的方法是定义一个指令来绑定(bind)滚动事件并查看位置。根据您的代码:
angular.module('ionicApp', ['ionic'])
.directive("scrollable", function() {
return function(scope, element, attrs) {
var container = angular.element(element);
container.bind("scroll", function(evt) {
if (container[0].scrollTop <= 0) {
alert('On the top of the world I\'m singing I\'m dancing.');
}
if (container[0].offsetHeight + container[0].scrollTop >= container[0].scrollHeight) {
alert('On the bottom of the world I\'m waiting.');
}
});
};
})
.controller('MyController', function($scope, $element) {
$scope.name = [{ ... }];
});

然后在您的 HTML 中添加指令
<div scrollable style="width:90%;height:1...

我更新了一个版本 on your plunker (v5)这对我有用,并且对于全局兼容性似乎非常强大。是不是低水平;)

替代库

如果你想实现一些更深层次的特性,你可以使用像 waypoint 这样的库。

Waypoints is a library that makes it easy to execute a function whenever you scroll to an element. http://imakewebthings.com/waypoints/



它也非常好用,非常轻巧,而且由于 v3.0 是免费的 jQuery :D。我知道一些铁杆前端设计师在使用它时没有任何性能问题。

关于angularjs - 当用户滚动到 Angular js中的div顶部时如何显示警报?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30725499/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com