How to show hidden div using url

前端 未结 2 983
盖世英雄少女心
盖世英雄少女心 2021-01-29 11:09

I\'m making a small page that has 3 sections. While 1 section is showing the others are hidden. When the page loads the welcome section is displayed, while the other sections ar

相关标签:
2条回答
  • 2021-01-29 11:16

    You could use window.location.hash* which will return the corresponding part of the url.

    For this to work you should give your <a> tags some proper hash value:

    <p><a href="#page1" id="menu-page1">Page 1</a></p>
    <p><a href="#page2" id="menu-page2">Page 2</a></p>
    

    And check the mentioned string whether it matches a given page:

    $(document).ready(function(){
        //binding click events to elements
    
        var locationHash = window.location.hash.substring(1);
        if(locationHash == 'page1'){
          $('#menu-page1').trigger('click');
        }else if(locationHash == 'page2'){
          $('#menu-page2').trigger('click');
        }
    });
    

    You see I used the click-events for a fast quick-n-dirty solution and also substringed location.hash to get rid of the #.
    Of course this is open for improvement .e.g. not hiding page1 or page2 at all on page load if a given hash is found.

    *See the linked document for Location as window.location is a Location object which holds a hashproperty

    0 讨论(0)
  • 2021-01-29 11:25

    You will need some javascript, that, on page loading, checks the URL for an anchor like #menu-xy, and makes the corresponding div visible.

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