How do I navigate to hashtag after page load?

后端 未结 5 1086
忘掉有多难
忘掉有多难 2021-02-01 07:38

I want to do the inverse of what I\'ve been finding so far. I\'m setting a lot of heights with js and I want to navigate to the hashtag in the url after the page has loaded. I\'

5条回答
  •  闹比i
    闹比i (楼主)
    2021-02-01 08:28

    Using scrollTo or scrollIntoView will not respect any offset created by the :target css selector, which is often used to make the page scroll to just above the anchor, by setting it to position: relative with a negative top.

    This will scroll to the anchor while respecting the :target selector:

    if (location.hash) {
        window.location.replace(location.hash);
    }
    

提交回复
热议问题