【问题标题】:Check if scrollIntoView is completed检查scrollIntoView是否完成
【发布时间】:2019-03-21 16:37:04
【问题描述】:

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

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

如何检查元素是否已完成滚动?我想避免 setTimeout 函数。

【问题讨论】:

标签: javascript angular typescript


【解决方案1】:

希望这会有所帮助..

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

});

【讨论】:

    【解决方案2】:

    基于an answer in this question,我能够为我的测试做这个......这假设你是@Injecting window 进入你的角度组件

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-07-22
      • 2010-12-06
      • 1970-01-01
      • 1970-01-01
      • 2015-10-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多