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';
}
});
}
|