How to make the page load to an anchor tag?

后端 未结 4 941
走了就别回头了
走了就别回头了 2020-12-31 17:04

how could I, or is it possible, to make it so when the webpage loads, the first thing it shows you is the part of the page, where the anchor tag is you want the person to fi

4条回答
  •  無奈伤痛
    2020-12-31 17:23

    A mix of these answers turned out to be the best option for me and has the advantage of being dynamic by pulling from the anchor from the URL and forcing the page to load at the intended destination:

    if (location.hash) location.href = location.hash;
    

    This was the cleanest solution for my project due to a number of other things running onload:

    JQuery:

    $(window).on("load", function() {
        if (location.hash) location.href = location.hash;
    }
    

    Vanilla:

    window.addEventListener('load', function() {
        if (location.hash) location.href = location.hash;
    }
    

提交回复
热议问题