检查scrollIntoView是否完成

时间:2018-10-17 04:42:38

标签: javascript angular typescript

我在Angular的单页应用程序中使用以下函数。单击菜单项时,滚动到相关的div。

  scroll(el) {
this.sharedService.isClicked.next(true);
el.scrollIntoView({ behavior: 'smooth', block: 'start'  });

}

如何检查元素是否已完成滚动?我想避免超时功能。

谢谢!

2 个答案:

答案 0 :(得分:0)

希望这会有所帮助。

  var scrollIntoviewCompleted = false;
  var currentVisible = false;
  var onceVisible = false;
  $(window).scroll(function(){
     $.fn.isOnScreen = function(){
        var element = this.get(0);
        var bounds = element.getBoundingClientRect();
        return bounds.top < window.innerHeight && bounds.bottom > 0;
    }
        if ($('.targetdiv').isOnScreen()) {
            currentVisible = true;
            onceVisible =true;
        } 
        else
        {
            currentVisible = false;
        }
        if(onceVisible == true && currentVisible == false){
            scrollIntoviewCompleted = true;
            console.log("scrollIntoViewCompleted");
        }

});

答案 1 :(得分:0)

基于an answer in this question,我能够在测试中使用它...并且假设您正在@Injectwindow插入角度分量

let win: Window;

const onScrollEnd = (fn: () => void): void => {
    let scrollTimeout: number | undefined;
    const listener = (): void => {
        win.clearTimeout(scrollTimeout);
        scrollTimeout = win.setTimeout(() => {
            win.removeEventListener('scroll', listener);
            fn();
        }, 100);
    };
    win.addEventListener('scroll', listener);
};

beforeEach(() => {
    //Standard component test setup stuff goes here...    

    win = TestBed.get('Window');
});

然后在我的测试中,我可以这样做:

it('should scroll the window down when...', (done: DoneFn) => {
    component.shouldScroll = true;
    fixture.detectChanges();

    onScrollEnd(() => {
        expect(win.scrollY).toBeGreaterThan(0);
        done();
    });
});