scrollIntoView with margin

后端 未结 5 1494
孤独总比滥情好
孤独总比滥情好 2021-02-19 08:14

I have a webpage on which I would like to scroll to a certain element.

That part works fine by using scrollIntoView; but I would like to add a bit of space

5条回答
  •  盖世英雄少女心
    2021-02-19 08:55

    Another potential solution is to scroll not the the element itself, but to one of its previous siblings. Example:

    let elementToScrollTo = ;
    const childOffset = 3;
    for (let i = 0; i < childOffset; i++) {
        if (!elementToScrollTo.previousElementSibling) {
           break;
        }
        elementToScrollTo = elementToScrollTo.previousElementSibling;
    }
    elementToScrollTo.scrollIntoView();
    

提交回复
热议问题