Javascript AngularJS 'scrollTop' 等价的?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26319551/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
AngularJS 'scrollTop' equivalent?
提问by pram
I'm looking to implement something similar to this in an AngularJS directive:
我希望在 AngularJS 指令中实现类似的东西:
https://github.com/geniuscarrier/scrollToTop/blob/master/jquery.scrollToTop.js
https://github.com/geniuscarrier/scrollToTop/blob/master/jquery.scrollToTop.js
It's fairly straightforward, when you are not at the top of the page it will fade in a button to scroll to the top:
这相当简单,当您不在页面顶部时,它会淡入一个按钮以滚动到顶部:
$(window).scroll(function() {
if ($(this).scrollTop() > 100) {
$this.fadeIn();
} else {
$this.fadeOut();
}
});
However I'm having a hard time finding how to get the current scroll location in Angular. I'd rather not have to use jQuery just for this single thing.
但是,我很难找到如何在 Angular 中获取当前滚动位置。我宁愿不必只为这件事使用 jQuery。
Thanks!
谢谢!
回答by Blaze
$window.pageYOffset
This is property from service $window
这是来自服务 $window 的属性
回答by HaukurHaf
I don't believe there's anything in Angular to get the scroll position. Just use plain vanilla JS.
我不相信 Angular 中有任何东西可以获取滚动位置。只需使用普通的香草 JS。
You can retrieve the scrollTop property on any element.
您可以检索任何元素上的 scrollTop 属性。
https://developer.mozilla.org/en-US/docs/Web/API/Element.scrollTop
https://developer.mozilla.org/en-US/docs/Web/API/Element.scrollTop
document.body.scrollTop
Fiddle for you: http://jsfiddle.net/cdwgsbq5/
为你小提琴:http: //jsfiddle.net/cdwgsbq5/
回答by Shankar ARUL - jupyterdata.com
Inject the $window into your controller and you can get the scroll position on scroll
将 $window 注入您的控制器,您可以在滚动时获取滚动位置
var windowEl = angular.element($window);
var handler = function() {
console.log(windowEl.scrollTop())
}
windowEl.on('scroll', handler);
Adaptation from another stackoverflow answer
改编自另一个stackoverflow 答案
回答by DMCISSOKHO
You can use
您可以使用
angular.element(document).bind('scroll', function() {
if (window.scrollTop() > 100) {
$this.fadeIn();
} else {
$this.fadeOut();
}
});
回答by fulabel
You can use like as polyfill here a link
您可以在此处使用类似 polyfill 的链接
function offset(elm) {
try {return elm.offset();} catch(e) {}
var rawDom = elm[0];
var _x = 0;
var _y = 0;
var body = document.documentElement || document.body;
var scrollX = window.pageXOffset || body.scrollLeft;
var scrollY = window.pageYOffset || body.scrollTop;
_x = rawDom.getBoundingClientRect().left + scrollX;
_y = rawDom.getBoundingClientRect().top + scrollY;
return { left: _x, top: _y };
}

