How to make the page load to an anchor tag?

后端 未结 4 938
走了就别回头了
走了就别回头了 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:14

    Something simple like this would do it

    <body onload=' location.href="#myanchor" '>
    <a id='myanchor' href='#'>anchor text</a>
    
    0 讨论(0)
  • 2020-12-31 17:23

    Use javascript.

    Solution 1

    When the document loads, go to the "hash" or anchor that you want

    <script type="text/javascript">
    function load()
    {
    window.location.hash="mylocation"; 
    }
    </script>
    

    Solution 2

    In the header:

    <script type="text/javascript" language="javascript">
        function moveWindow (){window.location.hash="mylocation";}
    </script>
    

    On the body tag:

    <body onload="moveWindow()">
    

    And your anchor:

    <a name="mylocation"></a>

    0 讨论(0)
  • 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;
    }
    
    0 讨论(0)
  • 2020-12-31 17:32

    Here's a 2018 update that's a bit more dynamic.

    If you'd like to pull the URL, pull the anchor from the URL, and move the page to that anchor, you can run this javascript on page load.

    if (window.location.href.indexOf('#') == 0) {
        let hash = window.location.href.split('#')[1];
        let hashTop = document.querySelector(`#${hash}`).offsetTop;
        window.scrollTop = hashTop;
    }
    

    There's also this way which is a bit more concise.

    if (location.hash) {
        let target = location.hash;
        window.scrollTop = document.querySelector(target).offsetTop;
    }
    

    If you're not compiling ES6 with babel, just change the let keyword to var. This also works for WordPress, which will add a slash in the URL before the anchor.

    0 讨论(0)
提交回复
热议问题