展开/折叠动画的菜单列表,并且只能使用CSS

展开/折叠动画的菜单列表,并且只能使用CSS

问题描述:

这是我想要做的:


  1. 点击PORTFOLIO;

  2. / li>
  3. 新链接流畅流畅;

  4. 再次点击PORTFOLIO,一切顺利;



    我当前的代码;

My current code;

$(function () {
    $('[data-toggle]').on('click', function () {
        var id = $(this).data("toggle"),
            $object = $(id),
            className = "open";

        if ($object) {
            if ($object.hasClass(className)) {
                $object.removeClass(className)
            } else {
                $object.addClass(className)
            }
        }
    });
});

#list {
    display: none;
}
#list.open {
    display: block;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<nav>
    <ul>
        <li><a href="#">Home</a> </li>
        <li><a href="#">A Empresa</a> </li>
        <li><a href="#" class="hide" data-toggle="#list">Portfolio</a>
            <ul id="list">
                <li><a href="#">Comerciais</a> </li>
                <li><a href="#">Residenciais</a> </li>
                <li><a href="#">Institucionais</a> </li>
                <li><a href="#">Edifícios</a> </li>
            </ul>
        </li>
        <li><a href="#">Contato</a> </li>
    </ul>
</nav>

可以完成这个没有JS,只有CSS?我没有任何线索,无论如何做的动画部分,我尝试CSS转换正常,但没有工作。

It's possible to accomplish this without JS, only with CSS? I have no clue whatsoever how to do the animation part, I tried CSS Transitions propriety, but didn't work.

还有,标记和JS的任何提示?

Also, any tips for the markup and JS? I don't thinks I'm doing it the "right way"... any tips would be appreciated.

这里是一开始。您需要跟踪类以确定何时反转例程。注意jQuery处理对象检查,所以你的 if 语句是不必要的。此外,在重复标记的情况下,我很少使用ID。使用相对选择器。

Here's a start. You'd need to track classes to determine when to reverse the routine. Note that jQuery handles object checking for you, so one of your if statements is unnecessary. Also, rarely do I use IDs in cases of repetitive markup. Use relative selectors instead.

nav ul ul {
    display: none;
    opacity: 0;
    transition: opacity 1s;
}
.in {
    opacity: 1;
}

$('nav li').click(function () {
    $(this).children('ul').slideToggle(function() {
        $(this).toggleClass('in out');
    });
});

演示

Demo

请注意,我有一个初始类 out $ c $

Note that I have an initial class out on the child lists elements.

更新:这是一个有手风琴效果的变体。

Update: Here's a variation with accordion effect.

$('nav').on('click', 'li', function () {
    $(this).children('ul').slideToggle(function() {
        $(this).toggleClass('in out');
    });

    $(this).siblings().find('ul').slideUp(function() {
        $(this).removeClass('in').addClass('out');
    });
});

演示

Demo