简体   繁体   English

jQuery 如果另一个 div 具有特定的 class,如何将 class 添加到一个 div

[英]jQuery How to add a class to a div if another div has specific class

if any of the webpage elements has is-open class, add open class to another div.如果任何网页元素具有is-open class,请将open class 添加到另一个 div。 doesn't work不起作用

is-open is added to div's each time a modal or tab is opened on the page.每次在页面上打开模式或选项卡时,都会将is-open添加到 div。

<script>
if($(".is-open").length){
$(".blur-screen").addClass("open");
} else {
$(".blur-screen").removeClass("open");    
}        
</script>

The code in your script runs immediately (before is-open is added to a div, because that only happens if a modal or tab is open, which probably doesn't happen immediately when page is loaded).脚本中的代码会立即运行(在将 is-open 添加到 div 之前,因为只有在模式或选项卡打开时才会发生这种情况,这可能不会在加载页面时立即发生)。

what you need to do is to call a function that will check it every time a modal/tab is opened您需要做的是调用 function 每次打开模式/选项卡时都会检查它

function checkIsOpen() {
  if($(".is-open").length){
    $(".blur-screen").addClass("open");
  } else {
    $(".blur-screen").removeClass("open");    
  }        
}

when modal/tab opens:当模态/标签打开时:

checkIsOpen();

Try this,试试这个,

if($("div").hasClass('is-open')){
  $(".blur-screen").addClass("open");
} else {
  $(".blur-screen").removeClass("open");    
} 

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

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