scrollIntoView Scrolls just too far

前端 未结 21 1913
盖世英雄少女心
盖世英雄少女心 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 11:04

    Position Anchor By Absolute Method

    Another way do do this is to position your anchors exactly where you want on the page rather than relying on scrolling by offset. I find it allows better control for each element (eg. if you want a different offset for certain elements), and may also be more resistant to browser API changes/differences.

    Now the offset is specified as -100px relative to the element. Create a function to create this anchor for code reuse, or if you are using a modern JS framework such as React do this by creating a component that renders your anchor, and pass in the anchor name and alignment for each element, which may or may not be the same.

    Then just use :

    const element = document.getElementById('anchor-name')
    element.scrollIntoView({ behavior: 'smooth', block: 'start' });
    

    For smooth scrolling with an offset of 100px.

提交回复
热议问题