Javascript 固定了滚动条上的元素,但不知道scrollTop()位置
我希望在屏幕顶部有一个固定的标题,而不知道Javascript 固定了滚动条上的元素,但不知道scrollTop()位置,javascript,Javascript,我希望在屏幕顶部有一个固定的标题,而不知道scrollTop()位置,因为它是可变的(标题上面有一个高度可变的元素) 由于offset().top,我将垂直间隔的值保存在一个变量中,问题是当表头固定在顶部时,该值变为0。所以我不能删除我以前添加的类 var win = $(window); win.on('load scroll resize', function(){ var header = $('#header-v1'), ht = header.of
scrollTop()
位置,因为它是可变的(标题上面有一个高度可变的元素)
由于offset().top
,我将垂直间隔的值保存在一个变量中,问题是当表头固定在顶部时,该值变为0
。所以我不能删除我以前添加的类
var win = $(window);
win.on('load scroll resize', function(){
var header = $('#header-v1'),
ht = header.offset().top, // Get the offset from the top
st = win.scrollTop(),
height = ht - st; // Get the offset from the top of the viewable screen
var get_h = 1,
j;
if (st <= ht) {
for (j = 0; j < height; j++) {
get_h += 1;
}
} else if (st >= get_h) {
header.addClass("fixed-nav");
} else {
header.removeClass("fixed-nav");
}
});
由于jQuery函数
one()
,我可以自己修复它
代码正在此处运行:。尝试更改CSS中顶栏
的高度,并查看如何使用确定的偏移量将菜单
固定在顶部
var win = $(window),
header = $('#header-v1'),
ht = header.offset().top;
win.on('scroll', function(){
var st = win.scrollTop();
ht = header.offset().top;
if (st >= ht) {
header.addClass("fixed-nav");
} else if (st < ht) {
header.removeClass("fixed-nav");
}
});
var win = $(window),
header = $('#header-v1');
var ht;
// Get the offset from the top into another scroll event
// ... using the function "one()".
win.one('scroll', function(){
ht = header.offset().top;
});
win.on('scroll', function(){
var st = win.scrollTop();
if (st >= ht) {
header.addClass("fixed-nav");
} else if (st < ht) {
header.removeClass("fixed-nav");
}
});
win.on("load resize",function(){
// Get the offset
win.one('scroll', function(){
ht = header.offset().top;
});
$(".navbtn").toggle(function() {
// The user clicks to show more content, get the offset again
win.one('scroll', function(){
ht = header.offset().top;
});
}, function () {
// Get the offset again when the content is hidden
win.one('scroll', function(){
ht = header.offset().top;
});
});
});