[英]Stick div to top of page when start scrolling
I have tried to make a div (id="hoe") that sticks to the top of the from the moment the user scrolls. 我试图制作一个div(id =“ hoe”),该div从用户滚动起就一直停留在顶部。 before scrolling, the div is located under the header.
滚动之前,div位于标题下方。 Unfortunately, i can't get it to work after lot's of trying.
不幸的是,经过大量尝试,我无法使其正常工作。 Any tips and help on what I do wrong is greatly appreciated.
对于我做错的任何提示和帮助,我们深表感谢。 Here is my code in a test version:
这是我在测试版本中的代码:
<!DOCTYPE html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" />
<style type="text/css">
#header
{
background-color: blue;
width: 100%;
height: 125px;
}
#hoe
{
background-color: red;
height: 180px;
width: 100%;
z-index: 9999;
top: 125;
position: fixed;
}
#een
{
margin-top: 180px;
background-color: green;
height: 700px;
width: 100%;
}
</style>
<script type="text/javascript">
$(document).ready(function() {
if ($('body').hasClass('lock')) {
bar_pos = $('#hoe').offset();
if (bar_pos.top >= (125+180)) {
$('#hoe').css('top', 0);
//document.getElementById("hoe").style.top="0"; also tried this
}
});
});
</script>
</head>
<body class="lock">
<div id="header">
</div>
<div id="hoe">
</div>
<div id="een">
</div>
</body>
</html>
I've modified your code and created a fiddle here: http://jsfiddle.net/UcX4A/ 我已经修改了您的代码,并在此处创建了一个小提琴: http : //jsfiddle.net/UcX4A/
There was a surplus bracket in your javascript 您的JavaScript中有多余的括号
$(document).ready(function() {
if ($('body').hasClass('lock')) {
bar_pos = $('#hoe').offset();
if (bar_pos.top >= (125+180)) {
$('#hoe').css('top', 0);
//document.getElementById("hoe").style.top="0"; also tried this
}
}); <<< Surplus bracket
});
Also, the "scroll" event wasn't attached to anything, so wasn't being evaluated. 此外,“滚动”事件没有附加任何内容,因此也没有进行评估。 I changed your:
我更改了您的:
$(document).ready(function() {
To a: 到:
$(window).scroll(function() {
See this: http://jsfiddle.net/WTnEd/ 看到这个: http : //jsfiddle.net/WTnEd/
Use $(window).scroll() 使用$(window).scroll()
$(document).ready(function () {
var bar_pos;
$(window).scroll(function (e) {
if ($('body').hasClass('lock')) {
bar_pos = $('#hoe').offset();
if (bar_pos.top >= (125 + 180)) {
$('#hoe').css('top', 0);
}
else{
$('#hoe').css('top', 125);
}
};
});
});
As I understand the question, this is an alternate way to stick div to top of page when start scrolling: 据我了解的问题,这是在开始滚动时将div粘贴到页面顶部的另一种方法:
<div id="header" style="position:fixed; top:0px; left:0px; right:0px;
height:100px; z-index:2; background:blue;"></div>
<div id="hoe" style="position:fixed; top:100px; left:0px; right:0px;
height:100px; z-index:2; background:red;"></div>
<div id="een" style="position:absolute; top:200px; left:0px; right:0px;
height:100px; z-index:1;">
<p>dummy text</p>
<p>dummy text</p>
<p>dummy text</p>
</div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.