<style type="text/css">
div {
width: 100%;
height: 100px;
margin-bottom: 15px;
background-color: pink;
}
#red {
background-color: red;
}
body {
height: 3000px;
}
</style>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div id="red"></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<script>
var oDiv = document.getElementById("red");
var otop = oDiv.offsetTop;
window.onscroll = function() {
var oheight = document.documentElement.scrollTop || document.body.scrollTop;
if (otop < oheight) {
oDiv.style.position = "fixed";
oDiv.style.top = 0;
} else {
oDiv.style.position = "relative";
}
}
</script>