[英]Fixed position of a div below header while page scrolling
我想在标题下有一个div来在滚动时占据顶部固定位置。 如果页面向上滚动,则标题也需要显示。
的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在这里。
在上面的小提琴中,绿色部分(.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)
引用窗口并进行比较
感谢@A。 Wolff使用.toggleClass()
很大程度上重构了代码
$(window).scroll(function() {
$(".converter").toggleClass("fixed-pos", $(this).scrollTop() > 100);
});
这可以为您工作:
$(document).ready(function() {
$( window ).scroll(function() {
var defaultPosition = $('.header').offset().top + $('.header').outerHeight();
if($(window).scrollTop() > defaultPosition){
$( ".converter" ).addClass("fixed-pos");
} else {
$( ".converter" ).removeClass("fixed-pos");
}
});
});
您可以使用CSS来做到这一点...根本不需要jquery
.header {
height:100px;
background:#ffe1d8;
width:100%;
position:fixed;
}
.converter {
height:100px;
margin-top:100px;
background:#9fff42;
width:100%;
position:fixed;
}
.content {
width:100%;
background:#faff70;
min-height:800px;
}
不确定您的结果应该是什么。 但是也许是这样的:
(function () {
var scrollMinimum = 0; // minimum scroll offset to fix the bar
var $scrollTopBar = $('.converter');
var $win = $(window);
var visible = false; // whether the bar is currently shown
$win.on('scroll', function(){
if (visible == false && $win.scrollTop() > scrollMinimum){
visible = true;
$scrollTopBar.addClass('fixed-pos');
} else if (visible == true && $win.scrollTop() <= scrollMinimum) {
visible = false;
$scrollTopBar.removeClass('fixed-pos');
}
});
})();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.