scrollIntoView Scrolls just too far

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

    Assuming you want to scroll to the divs that are all at the same level in DOM and have class name "scroll-with-offset", then this CSS will solve the issue:

    .scroll-with-offset {    
      padding-top: 100px;
      margin-bottom: -100px;
    }
    

    The offset from the top of the page is 100px. It will only work as intended with block: 'start':

    element.scrollIntoView({ behavior: 'smooth', block: 'start' });
    

    What's happening is that the divs' top point is at the normal location but their inner contents start 100px below the normal location. That's what padding-top:100px is for. margin-bottom: -100px is to offset the below div's extra margin. To make the solution complete also add this CSS to offset the margins/paddings for the top-most and bottom-most divs:

    .top-div {
      padding-top: 0;
    }
    .bottom-div {
      margin-bottom: 0;
    }
    

提交回复
热议问题