scrollIntoView Scrolls just too far

前端 未结 21 2102
盖世英雄少女心
盖世英雄少女心 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条回答
  •  猫巷女王i
    2020-12-07 11:03

    Fix it in 20 seconds:

    This solution belongs to @Arseniy-II, I have just simplified it into a function.

    function _scrollTo(selector, yOffset = 0){
      const el = document.querySelector(selector);
      const y = el.getBoundingClientRect().top + window.pageYOffset + yOffset;
    
      window.scrollTo({top: y, behavior: 'smooth'});
    }
    

    Usage (you can open up the console right here in StackOverflow and test it out):

    _scrollTo('#question-header', 0);
    

    I'm currently using this in production and it is working just fine.

提交回复
热议问题