gpt4 book ai didi

javascript - 使 div 元素粘在屏幕顶部

转载 作者:行者123 更新时间:2023-12-02 07:41:08 24 4
gpt4 key购买 nike

我写了一个脚本来检测我何时到达作为导航栏的 div 元素,然后我将它的 css 更改为固定位置和顶部 0,这样它就会固定在顶部,但问题是它不会那,它的作用就像滚动到顶部并跳转到屏幕的开头。 (闪烁)

Javascript

        var currentScrollTop = 0;
var barMenuOriginalTopPos = $('#navigation').offset().top;
console.log('original:' + barMenuOriginalTopPos);
$(window).scroll(function() {

currentScrollTop = $(window).scrollTop();
console.log(currentScrollTop);
if(currentScrollTop >= barMenuOriginalTopPos && $('#navigation').hasClass('fixElementToTop') == false){
$('#navigation').addClass('fixElementToTop');
}
else if(currentScrollTop < barMenuOriginalTopPos && $('#navigation').hasClass('fixElementToTop') ){
$('#navigation').removeClass('fixElementToTop');
}
});

CSS

.fixElementToTop { position: fixed; top:0; z-index:100;}

为什么

最佳答案

这里是通过 jQuery 插件实现的非闪烁解决方案:

$(document).ready(function() {
$('#fixedElement').scrollToFixed({ marginTop: 0 });
});

实例:http://bigspotteddog.github.com/ScrollToFixed/
插件的网站:https://github.com/bigspotteddog/ScrollToFixed/

关于javascript - 使 div 元素粘在屏幕顶部,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11070740/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com