Single page hide/show section based on current position

前端 未结 4 484
陌清茗
陌清茗 2021-01-15 01:40

I\'m working on a single page websites with each page organized into section tags. Every section is placed on top of each other. I need a way with jquery, where based on cur

相关标签:
4条回答
  • 2021-01-15 02:32

    Add an id to the links

    <li><a id="about" href="#about">About</a></li>
    

    Add an id to the section

    <section id="about-content">
    

    Add some jquery

    $("#about").click(function(){
        $("#about-content").show()
        $("#services-content").hide()
        $("#contact-content").hide()
    })
    

    WORKING EXAMPLE HERE

    0 讨论(0)
  • 2021-01-15 02:35

    You should give each section an id, ie. <section id="about">.

    Change your css for section to include a display: none attribute

    Use the following JS code:

    $(document).ready(function() {
        $('section').eq(0).show();
        $('navbar-nav').on('click', 'a', function() {
            $($(this).attr('href')).show().siblings('section:visible').hide();
        });
    });
    

    Or if you follow strict ordering (ie. about is first, services second, etc.):

    $(document).ready(function() {
        $('section').eq(0).show();
        $('.navbar-nav').on('click', 'li', function() {
            $('section').eq($(this).index()).show().siblings('section:visible').hide();
        });
    });
    

    Either method allows for dynamic content, although personally I'd use the last method.

    0 讨论(0)
  • 2021-01-15 02:36

    You can achieve this simply by registering hashchange callback where hash part of the current window.location is read. You can choose different DOM selection technique than id.

    <script>
        $( document ).ready(function() {
            $("section").hide();
    
            $(window).on("hashchange", function(){
                var hash = window.location.hash.substring(1); // hash part of url withou the first letter (#)
                $("section").hide();
                $("#"+hash).show();
            });
        });
    </script>
    

    Note that ids which are used for hidding and unhiding elements are also added.

    <section id="about">
    
    0 讨论(0)
  • 2021-01-15 02:37

    Using data-index instead of #id.

    Add the data-index on all li

    <ul class="nav navbar-nav">
        <li data-index="about"><a href="#about">About</a></li>
        <li data-index="services"><a href="#services">Services</a></li>
        <li data-index="contact"><a href="#contact">Contact</a></li>
    </ul>
    

    and then do the same for the sections

    <section class="content" data-index="services">
        ....
    </section>
    

    See this working fiddle for more details

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