分享

js实现在滚动页面时层智能浮动smartFloat

 滕王阁岳阳楼 2014-07-09

原理:

1、浏览器向下滚动时,当document的scrollTop大于浮动层离窗口顶部的距离时,就让浮动层的position属性设为fixed定位,脱离文档流

2、浏览器向上滚动时,当document的scrollTop小于浮动层离窗口顶部的距离时,就让浮动层的position属性设为static定位,回归文档流


新建一个html文档
把下面的html与CSS内容复制进相应的地方

<div style=”height: 30px; background: #ccc;”></div>
<div id=”inner”>
<p>智能浮动层,往下拖动滚动条,永远在这里</p>
</div>
<div style=”height: 2000px;”></div>
<style type=”text/css”>
#inner{
margin-top:10px;
width: 300px;
height: 100px;
padding: 8px;
line-height: 22px;
text-align:justify;
color: #000000;
border:1px solid #ffecb0;
background:rgba(255,254,224,.7);
box-shadow:2px 2px 7px rgba(0,0,0,.2);/*阴影*/
border-radius: 4px; /*圆角*/
}
</style>

开始写JS代码
1、先写一个获取元素距离顶部距离的函数
//原理很简单,通过递归检查是否存在父元素,累加起来得到距离值
function getTop(e){
var offset = e.offsetTop;
if(e.offsetParent != null) offset += getTop(e.offsetParent);
return offset;
}

2、接着写下面的代码
//先把浮动层对象存在一个变量中,方便后面调用
var obj = document.getElementById(“inner”); //b为漂浮层的id
//获取浮动层元素离窗口顶部的距离
var top = getTop(obj);
3、给窗口绑定滚动事件
window.onscroll = function(){
//获取窗口的scrollTop
var bodyScrollTop = document.documentElement.scrollTop || document.body.scrollTop;

if (bodyScrollTop > top){
/*当窗口的滚动高度大于浮动层距离窗口顶部的距离时,也就是原理中说的第一种情况
*我们把这个浮动层position值设为fixed,top值设为0px,让它定位在窗口顶部*/
obj.style.position = “fixed”;
obj.style.top = “0px”;
} else {
/*当窗口的滚动高度小于浮动层距离窗口顶部的距离时,也就是原理中说的第一种情况
*我们把这个浮动层position值设为static或为空,让它回归文档流
*让它回到原来的位置上去*/
obj.style.position = “static”;
}
}
4、兼容IE6
首先在前面加上判断浏览器是否是IE6的语句
//判断浏览器是否是IE6
var isIE6 = /msie 6/i.test(navigator.userAgent);
5、改动下窗口滚动事件绑定的函数的两句
//……
if (bodyScrollTop > top){
//如果是IE6,就设置position为absolute,否则设为fixed
obj.style.position = (isIE6) ? “absolute” : “fixed”;
//如果是IE6,就设置top值为bodyScrollTop,否则top为0
obj.style.top = (isIE6) ? bodyScrollTop + “px” : “0px”;
} else {
//……
JS完整代码如下

<script language=”javascript”>
(function(){
var obj = document.getElementById(“inner”);
var top = getTop(obj);
var isIE6 = /msie 6/i.test(navigator.userAgent);
window.onscroll = function(){
var bodyScrollTop = document.documentElement.scrollTop || document.body.scrollTop;
if (bodyScrollTop > top){
obj.style.position = (isIE6) ? “absolute” : “fixed”;
obj.style.top = (isIE6) ? bodyScrollTop + “px” : “0px”;
} else {
obj.style.position = “static”;
}
}
function getTop(e){
var offset = e.offsetTop;
if(e.offsetParent != null) offset += getTop(e.offsetParent);
return offset;
}
})()
</script>

 

查看实例 smartfloat.html

 


2



打签? ,   评论? 抢沙发

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多