javascript 滚动 100 像素后将 div 位置设置为固定?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11341177/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 12:51:10  来源:igfitidea点击:

set div position to fixed after scrolling 100px?

javascriptjquery

提问by user1481850

I tried to use the following function in order to set the div's position to 100 px from top after scrolling 100 px.

我尝试使用以下函数,以便在滚动 100 像素后将 div 的位置设置为距顶部 100 像素。

<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$(window).scroll(function(){
    $("#header").css("top",Math.max(0,100-$(this).scrollTop()));
});
</script>
<div class="header"  style="position:fixed;top:100px;background-color:red">something</div>

it is not working(the div stick to it's fixed position). it seems that the function is not relating to the div. what is my problem ?

它不工作(div 坚持它的固定位置)。该功能似乎与 div 无关。我的问题是什么?

回答by kuh-chan

Your problem ist that your divhas the classheader, not the id. Try <div id="header" style="position:fixed;top:100px;background-color:red">something</div>

你的问题是你divclass标题,而不是id. 尝试 <div id="header" style="position:fixed;top:100px;background-color:red">something</div>

回答by coolguy

$(document).ready(function(){
    $('.header').scroll(function(){
        $(this).css("top",Math.max(0,100-$(this).scrollTop()));
    });
});