scrollIntoView Scrolls just too far

前端 未结 21 2036
盖世英雄少女心
盖世英雄少女心 2020-12-07 10:08

I have a page where a scroll bar containing table rows with divs in them is dynamically generated from the database. Each table row acts like a link, sort of like you\'d see

21条回答
  •  独厮守ぢ
    2020-12-07 10:48

    Building on an earlier answer, I am doing this in an Angular5 project.

    Started with:

    // el.scrollIntoView(true);
    el.scrollIntoView({
       behavior: 'smooth',
       block: 'start'
    });
    window.scrollBy(0, -10); 
    

    But this gave some problems and needed to setTimeout for the scrollBy() like this:

    //window.scrollBy(0,-10);
    setTimeout(() => {
      window.scrollBy(0,-10)
      }, 500);
    

    And it works perfectly in MSIE11 and Chrome 68+. I have not tested in FF. 500ms was the shortest delay I would venture. Going lower sometimes failed as the smooth scroll had not yet completed. Adjust as required for your own project.

    +1 to Fred727 for this simple but effective solution.

提交回复
热议问题