[英]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.