我正在尝试使用 jQuery 折叠和关闭导航元素

Posted

技术标签:

【中文标题】我正在尝试使用 jQuery 折叠和关闭导航元素【英文标题】:I'm trying to collapse and close the nav element with jQuery 【发布时间】:2019-04-16 12:31:48 【问题描述】:

。我正在使用带有 gem coffee-rails 和 4.2.2 gem jquery-rails, 4.3.1 的 rails 5,但 animate 选项没有响应。

$(document).ready(function() 
  $('nav a.mobile_menu').on('click', function() 
    var currentNavHeight = $('nav').height();
    if (currentNavHeight < 6) 
      var newNavHeight = $('nav > ul').height() + 15;
      $('nav').animate(
        'height': newNavHeight + 'px'
      , 750);
     else 
      $('nav').animate(
        'height': '0px'
      , 750);
    
  );
);
nav 
  padding: 50px 15px 20px 15px;
  background-color: #4b0a0c;
  height: 0px;
  overflow: hidden;

【问题讨论】:

【参考方案1】:

你没有使用 jQuery 的 toggle() 方法有什么原因吗?

https://www.w3schools.com/jquery/tryit.asp?filename=tryjquery_eff_toggle

https://api.jquery.com/toggle/

【讨论】:

请不要使用 W3Schools 作为参考。他们的指南经常过时,有时甚至完全是错误的。处理 jQuery 时,请使用他们的参考:api.jquery.com。此外,OP 可能没有使用 toggle(),因为它不会像他们的逻辑尝试那样为元素设置动画。 slideToggle() 会更合适

以上是关于我正在尝试使用 jQuery 折叠和关闭导航元素的主要内容,如果未能解决你的问题,请参考以下文章