切换课程后将身高设定回零

切换课程后将身高设定回零

本文介绍了切换课程后将身高设定回零的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下HTML和JS.当您单击.slidedown-toggle时,它将在其父级(.slidedown)上切换类打开",并将高度应用于其同级(.nav-sub).这是可行的,但是当不存在"open"类时,将高度设置回0是不可行的.我想念什么?

I have the following HTML and JS. When you click the .slidedown-toggle it toggles the class 'open' on it's parent (.slidedown) and applies the height to it's sibling (.nav-sub). This is working, but what isn't working setting the height back to 0 when that 'open' class isn't present. What am I missing?

HTML

<li class="slidedown">
  <a href="#">Parent Link</a>
  <!-- Dropdown arrow -->
  <span class="slidedown-toggle">
    <span class="caret"></span>
  </span>
  <!-- Submenu -->
  <ul class="nav nav-sub">
    <li>
      <a href="#">Child Menu Item 1</a>
    </li>
  </ul>
</li>

JS

$(function navCollapse(){

  var slidedownToggle = $( '#global-nav .slidedown-toggle' );

  slidedownToggle.click( function() {
    var slidedown = $(this).parent( '.slidedown' );
    var navOpen = $( '#global-nav li.open' );
    var subnav = $(this).siblings( '.nav-sub' );
    var subnavHeight = subnav.height();

    slidedown.toggleClass( 'open' );

    if (navOpen){
      subnav.height( subnavHeight );
    }else{
      subnav.height( 0 );
    }

  });

});

推荐答案

$( '#global-nav li.open' )将返回一个始终为真的jQuery对象,您需要检查当前切换元素所属的li是否具有该类打开.

$( '#global-nav li.open' ) will return a jQuery object which will always be truthy, you need to check whether the li to which current toggle element belongs to has the class open.

您可以使用.closest()查找li元素,然后使用.hasClass()检查该类是否存在

You can use .closest() to find the li element and then use .hasClass() to check whether the class is present

$(function navCollapse() {

    var slidedownToggle = $('#global-nav .slidedown-toggle');

    slidedownToggle.click(function () {
        var slidedown = $(this).parent('.slidedown');
        var $li = $(this).closest('li');
        var subnav = $(this).siblings('.nav-sub');
        var subnavHeight = subnav.height();

        slidedown.toggleClass('open');

        if ($li.hasClass('open')) {
            subnav.height(0);
        } else {
            subnav.height(subnavHeight);
        }

    });

});

这篇关于切换课程后将身高设定回零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 05:41