<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>无标题文档</title>
<style>
body{
height:2500px;
padding:0;
margin:0;
}
#div1{
height:30px;
width:100%;
background:#0AF;
}
#div2{
height:30px;
width:100%;
background:red;
top:400px;
position:absolute;
}
</style>
</head>
<body>
<div id="div1">
顶部信息栏
</div>
<div id="div2">
留言信息
</div>
<script>
window.onscroll = function(){
var div2 = document.getElementById("div2");
var _top = document.documentElement.scrollTop || document.body.scrollTop;
if(_top > 400){
div2.style.position = "fixed";
div2.style.top = 0;
} else {
div2.style.position = "absolute";
div2.style.top = "400px";
}
}
</script>
</body>
</html>
我记得css里面的粘性定位好像也能做到顶部悬浮,这里是使用DOM做的。两个也是有些区别的,粘性定位的元素处于文档流当中,且粘性定位的兼容性较差。