我想在标题下方有一个 div,以便在滚动时占据顶部固定位置。如果页面向上滚动,那么 header 也需要显示。
CSS
.header {
height:100px;
background:#ffe1d8;
width:100%;
}
.converter {
height:100px;
background:#9fff42;
width:100%;
}
.content {
width:100%;
background:#faff70;
min-height:800px;
}
.fixed-pos {
position:fixed;
top:0;
z-index:1000;
}
HTML
<div class="header"> </div>
<div class="converter"> </div>
<div class="content"> </div>
jQuery
$(document).ready(function() {
$( window ).scroll(function() {
$( ".converter" ).addClass("fixed-pos");
if ($( ".converter" ).scrollTop(100 )) {
$( this ).removeClass("fixed-pos");
}
});
});
JsFiddle在这里。
在上面的 fiddle 中,绿色部分(.converter)向下滚动时占据顶部的固定位置。如果屏幕向上滚动,它占据与顶部相同的位置,隐藏其上方的标题(粉红色)。我希望在屏幕向上滚动到最顶部时显示 .converter div 上方的标题。
有什么帮助吗?
最佳答案
应该是
$(window).scroll(function() { //OnScroll, invoke
if($(this).scrollTop() > 100) {
//If the current scroll position is more than 100, add class
$( ".converter" ).addClass("fixed-pos");
} else {
//Else remove it
$( ".converter" ).removeClass("fixed-pos");
}
});
您的解决方案存在什么问题?首先,您直接在滚动条上添加类,而不是使用 if
条件而不是使用 应该使用 $(".converter")
$(this)
引用 window 并比较
感谢@A. Wolff使用 .toggleClass()
$(window).scroll(function() {
$(".converter").toggleClass("fixed-pos", $(this).scrollTop() > 100);
});
关于jquery - 页面滚动时标题下方的 div 的固定位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23788262/