AngularJS 'scrollTop' equivalent?

本小妞迷上赌 提交于 2019-12-04 17:38:13

问题


I'm looking to implement something similar to this in an AngularJS directive:

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.

Thanks!


回答1:


$window.pageYOffset

This is property from service $window




回答2:


I don't believe there's anything in Angular to get the scroll position. Just use plain vanilla JS.

You can retrieve the scrollTop property on any element.

https://developer.mozilla.org/en-US/docs/Web/API/Element.scrollTop

document.body.scrollTop

Fiddle for you: http://jsfiddle.net/cdwgsbq5/




回答3:


Inject the $window into your controller and you can get the scroll position on scroll

var windowEl = angular.element($window);
var handler = function() {
    console.log(windowEl.scrollTop())
}
windowEl.on('scroll', handler);

Fiddle

Adaptation from another stackoverflow answer




回答4:


You can use like as polyfill here a link

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 };
}



回答5:


You can use

angular.element(document).bind('scroll', function() {
    if (window.scrollTop() > 100) {
        $this.fadeIn();
    } else {
        $this.fadeOut();
    }
});


来源:https://stackoverflow.com/questions/26319551/angularjs-scrolltop-equivalent

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!