首页 > 解决方案 > 使用 jQuery 在基于另一个类的另一个 div 中添加一个类

问题描述

当另一个 div 使用 jQuery 具有“滚动到固定固定”类时,我正在尝试删除一个 div 类。滚动功能可以正常工作,并且粘性标题会根据需要显示。但它的条件似乎不起作用。我尝试了以下代码,但没有运气。请协助: :

$(window).scroll(function() {
  var scroll = $(window).scrollTop();

  var y = $(this).scrollTop();
  if (y > 10) {
    //clearHeader, not clearheader - caps H
    $(".scroll-nav-holder").addClass("scroll-to-fixed-fixed");
  } else {
    $(".scroll-nav-holder").removeClass("scroll-to-fixed-fixed");
  }
});

if ($('.scroll-nav-holder').hasClass('scroll-to-fixed-fixed')) {
  $(".logo-holder").removeClass('nodisplay');
} else {
  $(".logo-holder").addClass('nodisplay');
}
.logo-holder {
  height: 100px;
  background: red;
}

.nodisplay {
  display: none;
}

.scroll-nav-holder {
  height: 20px;
  background: blue;
}

.container {
  height: 200px;
  background: green;
}

.scroll-to-fixed-fixed {
  position: fixed;
  top: 0px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="logo-holder nodisplay">something here</div>

<div class="container">
  More stuff
</div>
<div class="container">
  More stuff
</div>
<div class="container">
  More stuff
</div>
<div class="container">
  More stuff
</div>
<div class="container">
  More stuff
</div>


<div class="scroll-nav-holder">
  somethin more here
</div>

标签: javascriptjqueryhtml

解决方案


如上所述,您应该在事件中包含您的.logo-header条件。此外,我使用toggleClassscroll函数稍微重构了您的代码,使其更简洁:

$(window).scroll(function() {
  var scroll = $(window).scrollTop(); // ?
	const toggleCondition = $(this).scrollTop() > 10;
	$(".scroll-nav-holder").toggleClass('scroll-to-fixed-fixed', toggleCondition);
	$(".logo-holder").toggleClass('nodisplay', toggleCondition);
});
.logo-holder {
  height: 100px;
  background: red;
}

.nodisplay {
  display: none;
}

.scroll-nav-holder {
  height: 20px;
  background: blue;
}

.container {
  height: 200px;
  background: green;
}

.scroll-to-fixed-fixed {
  position: fixed;
  top: 0px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="logo-holder nodisplay">something here</div>

<div class="container">
  More stuff
</div>
<div class="container">
  More stuff
</div>
<div class="container">
  More stuff
</div>
<div class="container">
  More stuff
</div>
<div class="container">
  More stuff
</div>


<div class="scroll-nav-holder">
  somethin more here
</div>


推荐阅读