[英]Position fixed on a div after scrolling for a predefined amount of px
I'm working on a "stupid" effect on my webpage that has a simple parallax effect. 我正在我的网页上制作一个具有简单视差效果的“愚蠢”效果。
I want #menu
to assume "position: fixed;"
我希望
#menu
假设"position: fixed;"
instead of "position: relative;"
而不是
"position: relative;"
after scrolling for the height of the header (so after 100px). 滚动后标题的高度(因此在100px之后)。
This is my code, at the moment: 这是我的代码,目前:
<!DOCTYPE html>
<html>
<head>
<title></title>
<style type="text/css">
body {
margin: 0;
}
header {
position: fixed;
top: 0;
width: 100%;
z-index: -1;
height: 100px;
background: green;
}
.wrapper {
margin-top: 100px;
margin-bottom: 60px;
}
.content {
position: relative;
z-index: 1;
border-top: 1px solid black;
border-bottom: 1px solid black;
background: white;
min-height: 1500px;
}
#menu{
width: 100%;
height: 50px;
background-color: red;
position: relative;
}
footer {
width: 100%;
position: fixed;
z-index: -1;
bottom: 0;
background: black;
color: white;
height: 60px;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript">
$(window).scroll(function(){
if ($(window).scrollTop() >= $(header).height()) {
$("#menu").css('position', 'fixed');
alert("I'm working fine.");
}
});
</script>
</head>
<body>
<div class="wrapper">
<header id="head">
<h1>HEADER</h1>
</header>
<div class="content">
<div id="menu">I SHOULD BE FIXED AFTER SCROLLING FOR 100px.</div>
<h1>CONTENT</h1>
</div>
<footer>
<h1>FOOTER</h1>
</footer>
</div>
</body>
</html>
It's like the JQuery script is not working and I don't know why 这就像JQuery脚本不起作用,我不知道为什么
Any help would be really appreciated, thanks in advance. 任何帮助将非常感谢,提前感谢。
here to select any HTML tag we use quotes ('html tag') - single quote
or ("html tag") - double quote
. 这里选择我们使用引号
('html tag') - single quote
任何HTML标签('html tag') - single quote
或("html tag") - double quote
。
Hence your new code will look like as below. 因此,您的新代码如下所示。
$(window).scroll(function(){
if ($(window).scrollTop() >= $('header').height()) {
$("#menu").css('position', 'fixed');
alert("I'm working fine.");
}
});
I ran it on my website. 我在我的网站上运行它。 The console caught the error.
控制台发现错误。 header is not defined.
标头未定义。 Change code in to this:
将代码更改为:
<script type="text/javascript">
$(window).scroll(function(){
if ($(window).scrollTop() >= $('#head').height()) {
$("#menu").css('position', 'fixed');
alert("I'm working fine.");
}
});
</script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.