HTML5開發(fā)項目實戰(zhàn):側(cè)邊欄固定
知識點:
1.事件處理(滾動事件)
2.獲取滾動的高度
3.獲取元素的高度
4.使用JS操作CSS改變樣式
5.absolute定位方式
側(cè)邊欄固定-JQuery方法:
<!DOCTYPE>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<script type="text/javascript">
var Getid=function(id){
return document.getElementById(id);
}
var addEvent=function(obj,event,fun){
if(obj.addEventListener){
obj.addEventListener(event,fun,false);
}else if(obj.attachEvent()){
obj.attachEvent("on"+event,fun);
}
}
var InSider=Getid("lesson-nav");
addEvent(window,"scroll",function(){
var scrollHeight=document.body.scrollTop;
//console.log(scrollHeight);
var contentHeight=Getid("changeid").offsetHeight-InSider.offsetHeight;//獲取的滾動的高度
//console.log(contentHeight);
if(scrollHeight>253 && scrollHeight<contentHeight+253){
InSider.style.position="absolute";
InSider.style.left="0px";
insider.style.top=scrollHeight-253 +"px";
}else if(scrollHeight<=253){
insider.style.position="absolute";
insider.style.left="0px";
insider.style.top="0px";
}
});
</script>
</body>
</html>
側(cè)邊欄固定-JQuery方法:
<!DOCTYPE>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<script type="text/javascript">
var jWindow=$(window);
jWindow.scroll(function(){
var scrollHeight=jWindow.scrollTop();
var contentHeight=$("#changeid").height()-$(".lesson-nav").height();
// console.log(scrollHeight+"---"+contentHeight);
if(scrollHeight >253 && scrollHeight<contentHeight+253){
$(".lesson-nav").css({
position:"absolute",
left:"0px",
top:scrollHeight-253 +"px"
});
}else if{
position:"absolute",
left:"0px",
top:"0px"
}
})
</script>
</body>
</html>