Open List Item with Scroll Spy

假如想象 提交于 2020-01-13 19:11:26

问题


I am trying to achieve the Scroll Spy style on the Bootstrap page. The style is a Tree Menu that expands when the Scroll Spy is active on that item.

I have created a simple affix menu and a little snippet of Java Script that works correctly except that it removes the hide class when scroll spy is on the first element. I just cannot figure out the correct argument to tell it when it has found the correct element on the scroll spy.

HTML:

<div class="row">
    <div class="col-sm-3 col-xs-3" id="nav">
        <ul class="nav list-group affix">
        <li class="list-group-item"><a href="#g1">Item 1</a></li>
        <li class="list-group-item"><a href="#g2">Item 2</a></li>
        <li class="list-group-item"><a href="#g3">Item 3</a>
            <ul class="yep">
                <li class="list-group-item child hide"><a href="#g3">Item a</a></li>
                <li class="list-group-item child hide"><a href="#g3">Item b</a></li>
            </ul>
        </li>
        <li class="list-group-item"><a href="#g4">Item 4</a></li>
        <li class="list-group-item"><a href="#g5">Item 5</a></li>
        </ul>
    </div>
    <div class="col-sm-9 col-xs-9">
        <section id="g1">
            Content 1
        </section>

        <section id="g2">
            Content 2
        </section>

        <section id="g3">
            Content 3
        </section>

        <section id="g4">
            Content 4
        </section>

        <section id="g5">
            Content 5
        </section>
    </div>

</div>

JS:

$( document ).ready(function() {
        $('body').scrollspy({ 'target': '#nav', 'offset': 10 });

        $('#nav').on('activate.bs.scrollspy', function() {

            if ($('ul').is('.yep') && $('li').is('.hide') && $('li').is('.child')) {
                    $('li').removeClass('hide');
            }
            else{
                $('ul').addClass('show');
                console.log("Yeah");
            }

            $(this).parent().children('ul.tree').toggle(200);

        });
    });

Current running version is on this Bootply.


回答1:


Try this..

  $('#nav').on('activate.bs.scrollspy', function() {

    var ele = $(this).find('.active');

    if (ele.find('.yep').length>0) {
      $('.yep li').removeClass('hide');
    }
    else{
      $('.yep li').addClass('hide');
    }

  });

Updated Bootply: http://bootply.com/95998



来源:https://stackoverflow.com/questions/20136269/open-list-item-with-scroll-spy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!