scrollIntoView with margin

后端 未结 5 1505
孤独总比滥情好
孤独总比滥情好 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条回答
  •  萌比男神i
    2021-02-19 08:42

    You can always use scrollTo by first getting the elements coordinates using getBoundingClientRect then adding the scroll offset and taking your scroll margin. e.g.

    const moveToBlue = () => {
      const blue = document.getElementById('blue');
      let position = blue.getBoundingClientRect();
      // scrolls to 20px above element
      window.scrollTo(position.left, position.top + window.scrollY - 20);
    };
    

提交回复
热议问题