您的位置:首页 > Web前端 > JavaScript

Javascript样例之文档章节滚动全版(DOM)

2016-07-12 15:05 309 查看
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
body{
margin: 0;
background-color: #dddddd;
}
.w{
margin: 0 auto;
width: 980px;
}
.pg-header{
background-color: black;
color: white;
height: 48px;
}
.pg-body .menu{
position: absolute;
left: 200px;
width: 180px;
background-color: white;
float: left;
}
.pg-body .menu .active{
background-color: #425a66;
color: white;

}
.pg-body .fixed{
position: fixed;
top: 10px;
}
.pg-body .content{
position: absolute;
left: 385px;
right: 200px;
background-color: white;
float: left;
}
.pg-body .content .item{
height: 900px;
}
</style>
</head>
<body onscroll="Hua();">
<div class="pg-header">
<div class="w">

</div>
</div>
<div class="pg-body">
<div id="menu" class="menu">
<ul>
<li>第一章</li>
<li>第二章</li>
<li>第三章</li>
</ul>
</div>
<div id="content" class="content">
<div class="item">床前明月管</div>
<div class="item">疑是地上霜</div>
<div class="item" style="height: 100px;">我是郭德纲</div>
</div>
</div>
<script>
function Hua(){
var a = document.body.offsetHeight;
var b = document.getElementById('content').offsetHeight;
var c = document.documentElement.clientHeight;//当前可视高度

var huaGao = document.body.scrollTop;//当前从body滑动的高度
console.log(a, b, huaGao, c)
var caiDan = document.getElementById('menu');
if(huaGao>48){
caiDan.classList.add('fixed');
}else{
caiDan.classList.remove('fixed');
}

var items = document.getElementById('content').children;//获取【子div】
for (var i=0;i<items.length;i++){//一章对应一个div一个内容
var currentItem = items[i];//得到每个div内容
//当前标签距离body的高度
var currentItemBodyTop = currentItem.offsetTop + currentItem.offsetParent.offsetTop;////当前标签距离父级div的高度+父级div距离body的高度
var currentItemWindowTop = currentItemBodyTop - huaGao;//得到剩下的高度
//                        console.log(currentItemWindowTop);
var currentHeight = currentItem.offsetHeight;//可视范围的自身高度?为什么不是scrollHeight
var bottomHeight = currentItemBodyTop+currentHeight;//获取当前文档底部到body的总高度

if((a+b)==(huaGao+c)){
var mu = document.getElementById('menu').children[0].lastElementChild;
var lis = document.getElementById('menu').getElementsByTagName('li');
for (var m=0;m<lis.length;m++) {
var current_list = lis[m];
if(current_list.getAttribute('class')=='active'){
current_list.classList.remove('active');
break;
}
}
mu.classList.add('active');
return
}

if (currentItemWindowTop<0 && huaGao < bottomHeight){
var ziJi = caiDan.getElementsByTagName('li')[i];//得到第一章
console.log(ziJi)//<li class=​"active">​第二章​</li>​
ziJi.className = 'active';
var lis = caiDan.getElementsByTagName('li');
console.log(lis)//[li.active, li, li]
for(var j=0;j<lis.length;j++){
if(ziJi == lis[j]){

}else{
lis[j].classList.remove('active')
}
}
break;
//                        caiDan.getElementsBytagName('li')[i].className = 'active';
}

}
}
</script>
</body>
</html>


代码
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: