[英]Div not getting fixed on scrolling
I am trying to make a div
fixed to top when I scroll down. 向下滚动时,我试图将
div
固定在顶部。 But somehow the code is not working... 但是以某种方式代码无法正常工作...
Please check the code below: 请检查以下代码:
<div id="column-left" class="column_absolute">
My name is Peter
</div>
<script type="text/javascript">
function window_onload() {
alert("hi");
window.addEventListener("scroll", navbar_reset_top, false);
}
var navbar_top = 100;
function navbar_reset_top() {
var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
if (scrollTop > navbar_top && column-left.className === "column_absolute") {
document.getElementById("column-left").className="column_fixed";
}
else if (scrollTop < navbar_top && column-left.className === "column_fixed") {
document.getElementById("column-left").className="column_absolute";
}
}
</script>
<style type="text/css">
.column_absolute {
width: 220px;
padding: 0px 15px 0 0px;
border-right: 1px solid #eee;
margin-left:20px;
position:absolute;
}
.column_fixed {
width: 220px;
position:fixed;
margin-top:0px;
padding: 0px 15px 0 0px;
border-right: 1px solid #eee;
}
</style>
</head>
<body onload="javascript:window_onload()">
When I'm scrolling down, the div
mentioned above should be fixed. 当我向下滚动时,上面提到的
div
应该是固定的。
Please check the code and correct me please... 请检查代码并更正我...
Everything works fine in your code, except that you have undefined variable column-left
. 除了具有
undefined variable column-left
之外,其他所有代码都可以正常工作。 Probably you missed defining it. 可能您错过了定义它的时间。
Demo: http://jsfiddle.net/GCu2D/137/ 演示: http : //jsfiddle.net/GCu2D/137/
function window_onload() {
alert("hi");
document.addEventListener("scroll", navbar_reset_top, false);
}
var navbar_top = 100;
function navbar_reset_top() {
var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
var column_left = document.getElementById("column-left");
if (scrollTop > navbar_top && column_left.className === "column_absolute") {
document.getElementById("column-left").className = "column_fixed";
} else if (scrollTop < navbar_top && column_left.className === "column_fixed") {
document.getElementById("column-left").className = "column_absolute";
}
}
I used column_left
instead of column-left
我用
column_left
而不是column-left
the id of the div is column_fixed. div的ID为column_fixed。 you should use # insead of .
您应该使用#insead of。 in your css class to use id selector.
在CSS类中使用ID选择器。
#column_fixed
{
width: 220px;
position:fixed;
margin-top:0px;
padding: 0px 15px 0 0px;
border-right: 1px solid #eee;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.