JS固定侧边栏教程总结

论坛 期权论坛 脚本     
匿名技术用户   2021-1-4 02:48   11   0

JS固定侧边栏教程总结

教程来自慕课网http://www.imooc.com/video/1019


固定侧边栏的基本思路:

计算侧边栏的实际高度,当滚动高度+可视页面高度大于侧边栏实际高度时,用JS的CSS文档化改变侧边栏的position为fixed

scrollHeight+screenHeight > sideHeight

/**
 * Created by jacelyn on 2016/2/12.
 */
window.onload = function(){
    var $ = function(id){
        return document.getElementById(id);
    }

    var addEvent = function(obj, event, fn){
        if(obj.addEventListener){
            obj.addEventListener(event,fn,false);
        }else if(obj.attachEvent){
            obj.attachEvent('on'+event,fn);
        }

    }

    var domSider = $('sidebar');
    addEvent(window,'scroll', function(){
        var sideHeight = domSider.offsetHeight;
        var screenHeight = document.documentElement.clientHeight;
        var scrollHeight = document.body.scrollTop;
        if(scrollHeight+screenHeight > sideHeight){
            domSider.style.cssText='position:fixed;' +
                'right:0px;top:'+(-(sideHeight-screenHeight))+'px';
        }else{
            domSider.style.position='static';
        }
    });
}


分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:7942463
帖子:1588486
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP