简体   繁体   English

jQuery hasClass和if语句

[英]jQuery hasClass and if statement

I'm having issues trying to get this code to run properly. 我在尝试使此代码正常运行时遇到问题。 I have a div element called .collapsible-menu and I need to change its z-index when it becomes active. 我有一个名为.collapsible-menu的div元素,当它变为活动状态时,我需要更改其z-index。 When the menu is clicked the class, 'menu-active' is added to the body through some other js. 单击菜单上的类后,“菜单激活”将通过其他一些js添加到正文中。

This is what I have: 这就是我所拥有的:

jQuery(document).ready(function($){
  if ($("body").hasClass('menu-active')) {
     $(".collapsible-menu").css("zIndex", 100);
  } else {
     $(".collapsible-menu").css("zIndex", 3);
  }
});

Does this require me to use a mutation observation due to the class being added in after the documents been loaded? 由于在加载文档后添加了类,这是否需要我使用突变观察? If so, is this on the right path? 如果是这样,这是否在正确的道路上?

var observer = new MutationObserver(function(mutations) {
      mutations.forEach(function(mutation) {
         if ($("body").hasClass('menu-active')) {
            $(".collapsible-menu").css("zIndex", 100);
         } else {
            $(".collapsible-menu").css("zIndex", 3);
         }
         console.log(mutation.type);
     });    
});

You should use CSS. 您应该使用CSS。

.collapsible-menu{
   z-index: 3;
}
.menu-active .collapsible-menu{
   z-index: 100;
}

If you can do something using the CSS , it is almost always better solution than using JavaScript 如果您可以使用CSS进行操作 ,那么它总是比使用JavaScript 更好的解决方案

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM