javascript - 使用 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>
解决方案
如上所述,您应该在事件中包含您的.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>
推荐阅读
- java - 拖动视图 onLongClick 并启动活动 onClick
- kubernetes - Kubernetes 节点内存限制
- javascript - 使用 Node Selenium 下载 Excel 文件
- shell - 用于创建 Hive 表的 Shell 脚本
- python - 无法设置竞争条件,我的代码是否按顺序运行?
- python - 如何在python环境中的linux文件中的特定模式或行号之后添加多行
- css - 悬停效果不支持 p 和 h1 标签
- nlp - Dialogflow - 用户能否为一个意图发送多个响应,而不触发另一个?
- linux - 如何按主机名而不是 instance_id 过滤以进行谷歌堆栈驱动程序日志记录?
- jenkins - Jenkins:从队列中的项目获取作业名称(通过 API)