滚动 冻结 div demo

原理看明白一点,但是关于那些top的位置,还是很模糊,这个demo是从太平洋扒下来的,有空再研究看看

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>滚动到顶部,锁定</title>
<style type="text/css">
.channelMove {
    overflow: hidden;
    position: fixed;
    top:0px;
    300px;
    z-index: 200;
}
#channelHtml {
  
    display: block;
 300px;
 height:500px;
    margin-bottom: 10px;
 border:  #000000 solid 1px;
}

</style>
</head>
<body>
<br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>
<div id="dMark" class="clear" style="visibility:hidden;margin-top:-1px;"></div>
<div id="channelHtml">

</div>
<br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>
</body>

<script type="text/javascript">
(function(){
$$ = function(id){return document.getElementById(id)}

function addClass(o,cn){var re = new RegExp("(\\s*|^)"+cn+"\\b","g");o.className +=o.className?(re.test(o.className)?"":" "+ cn):cn}
function removeClass(o,cn){var re = new RegExp("(\\s*|^)"+cn+"\\b","g");var sName = o.className;o.className = sName.replace(re,"")}

window.onscroll=window.onresize=function(){
//document.documentElement.scrollTop  获取当前页面的滚动条纵坐标位置
//document.body.scrollTop 网页被卷去的高
//document.documentElement.clientTop  返回文档或元素的厚度
//document.documentElement.getBoundingClientRect.top 获取页面元素的顶部位置
var scrTop = document.body.scrollTop;
var offTop = $$("dMark").getBoundingClientRect().top+scrTop-document.documentElement.clientTop;
scrTop>offTop?addClass($$("channelHtml"),"channelMove"):removeClass($$("channelHtml"),"channelMove");
}
})();
</script>

</html>

原文地址:https://www.cnblogs.com/shoupifeng/p/2641967.html