侧边栏滚动跟随--兼容IE7 safari chrome firefox

RT.

很多网站为了提高点击率,都会将最新的文章,或者是一些广告放在网页主体的侧边,当页面滑动到一定的位置之后,会固定在页面的顶部,保持不动.这种方式我们称之为侧边栏滚动跟随.

由于侧边栏不能够贴着屏幕边缘,所以不能够使用position:fixed来将其固定在屏幕边缘.

这里我搜到了一个方法,亲测可用且兼容:

(function(){
        var oDiv=document.getElementById("viewLeft");//此处传入需要定位的元素id,外面必须有一个侧边栏的最大的元素包住它
        var H=-41,iE6;//此处设置滑动到距离窗口顶部H距离之后固定该元素的高度值
        var Y=oDiv;
        while(Y){H+=Y.offsetTop;Y=Y.offsetParent;}
        iE6=window.ActiveXObject&&!window.XMLHttpRequest;
        if(!iE6){
            window.onscroll=function()
            {
                var s=document.body.scrollTop||document.documentElement.scrollTop;
                if(s>H){oDiv.className="viewLeft fixerer";if(iE6){oDiv.style.top=(s-H)+"px";}} //如果滑动到元素本身设定的位置,加上一个css样式,使其固定
                else{oDiv.className="viewLeft";}  //否则,还原其类名
            };
        }
    })();
当然,一般我们侧边栏都是在侧边,所以另一侧的内容,在滑动到相应位置后,必须将其css属性设置一个margin-right 或者margin-left值来保证其float属性不会让元素飞过去.插在飘起来的侧边栏元素下面.

可以在上面的onscroll函数中的if条件语句中如下设置$('.viewCenter').addClass('right');添加一个类名,然后在else条件语句下,移除加上的类名:$('.viewCenter').removeClass('right');

css文件设置:

.fixerer{
    position:fixed;
    _position:absolute;
    top:41px;
    z-index:250;
}
.right{
    margin-left:200px;
}
HTML代码
<!--左侧导航模块开始-->
<div class="leftView" id="leftView">
    <div class="viewLeft" id="viewLeft">
    <!--文章标题列表开始-->
    <div class="articleName">
        <span class="titleCN">{$name[0]['name']}</span>
        <br clear="all"/>
        <div id="articleTitleList1">
            <ul id="articleTitleList" name="articleTitleList" class="articleTitleList">
                <volist id="list" name="list" key="k">
                    <li class="articleItem" id="{$k}">
                        <a class="articleTitle" id="articleItem{$list['id']}" href="{$list['id']}.html">·  {$list['title']}</a>
                    </li>
                </volist>
            </ul>
        </div>
    </div>
    <!--文章标题列表结束-->
CSS

.leftView{
    float: left;
    position: relative;
}
.viewLeft{
    width:199px;
    border-left: 1px solid #eee;
    border-bottom: 1px solid #eee;
    height:auto;
    min-height: 553px;
    background: #f8faff;
}
.articleName{
    width:199px;
    height:300px;
    float:left;
    background: #f8faff;
    overflow: hidden;
}
.articleTitleList{
    min-height: 251px;
    list-style: none;
    display: block;
    border: none;
}
#articleTitleList1{
    overflow: hidden;
    height:250px;
    float: left;
    margin-left: 20px;
}
.articleItem{
    display: block;
    width:149px;
    margin:0 auto;
    padding:10px 0 10px 0;
    border-bottom: 1px dotted #ccc;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    font-size: 12px;
}
.articleTitle{
    text-decoration: none;
   color: #777;
    font-size:12px;
}
.articleTitle:hover{
    color:#AA0000;
}

侧边栏最外层必须要设置position:relative,float:left两个属性值.然后里面包含主要内容的div的id作为参数传入上面的js中.


猜你喜欢

转载自blog.csdn.net/killzero/article/details/38924929
今日推荐