javascript - 无法从 toggleClass jQuery 检索高度

标签 javascript jquery css function

我想获得切换类的高度。单击按钮时,将添加类 .category-menu-visible。如果类(class)存在,那么我想得到它的高度。但是当我提醒 menuHeight 时,它是 0。

Small scale JSFiddle example

实际代码:

jQuery

jQuery('.topics-btn').click(function(){
  jQuery('.category-menu-wrap').toggleClass('category-menu-visible');

  if (jQuery('.category-menu-wrap').hasClass('category-menu-visible')){
    var menuHeight = jQuery('.category-menu-visible').height();
    alert(menuHeight);
    jQuery('.sidebar .content-wrap').css('margin-top', menuHeight);
  } else {
    jQuery('.sidebar .content-wrap').css('margin-top', 0);
  }

});

CSS:

.category-menu-wrap {
  width:100%;
  height:0px;
  background-color:#F7D5B6;
  overflow: hidden;
  transition: height .5s cubic-bezier(.27,1.76,.95,1.19);
}
.category-menu-visible {
  height: 70px;
  transition: height .3s cubic-bezier(.27,1.76,.95,1.1);
}

为什么不能获取高度?

最佳答案

您需要等到转换完成。 更新: 有个有用的事件transitionend这样做:

jQuery('.topics-btn').click(function(){
  var $menu = jQuery('.category-menu-wrap');
  $menu.toggleClass('category-menu-visible');
  $menu.on("transitionend", function(){
    if (jQuery('.category-menu-wrap').hasClass('category-menu-visible')){
      var menuHeight = jQuery('.category-menu-visible').height();
      alert(menuHeight);
      jQuery('.sidebar .content-wrap').css('margin-top', menuHeight);
    } else {
      jQuery('.sidebar .content-wrap').css('margin-top', 0);
    }
  });

});
.category-menu-wrap {
  height: 0;
}
.category-menu-visible {
  height: 70px;
  transition: height .3s cubic-bezier(.27,1.76,.95,1.1);
}
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<button class='topics-btn'>Click</button>
<div class='category-menu-wrap'></div>

关于javascript - 无法从 toggleClass jQuery 检索高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45314636/

相关文章:

javascript - 使用 JavaScript 填充多个 DIV

javascript - 未捕获的 ReferenceError : $ is not defined when using $(document). 就绪

android - 使用导航栏模拟移动设备的 Chrome 开发工具

javascript - tsconfig.json : not input were found in config file?

javascript - 将 DateTimeOffset 持久化到服务器

javascript - Window.postMessage() 问题

javascript - Flot 问题中的时间图?

javascript - Ajax 调用 - PHP 返回值

html - Div 没有填满页面

html - 尝试使用 :hover on another pseudo class 更改导航项背景图像