运用onscroll事件//滚动窗口滚动条时触发

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>day08_作业讲解</title>
<style>
body{margin: 0;height:2000px;}
header{
height: 60px;
background: #f00;
}
.toolbar{height:300px;border: 1px solid #000;}
.fixed{position: fixed;top: 0;left: 0;right: 0;}
</style>
<script>
//页面加载时间
window.onload =function(){
//顶部悬浮(吸顶菜单)
//1)获取元素
var topNav = document.getElementById("topNav");
//2)当滚动到指定位置是给#topNav添加fixed类
//绑定滚动事件 (gunlun/拖动滚动条)时执行函数中的代码
window.onscroll = function(){
//console.log('1111');

//获取滚动条滚动过的距离
var scrollTop = document.body.scrollTop || document.documentElement.scrollTop;

// 当滚动到<指定位置>时给#topNav添加fixed类
if(scrollTop >= 302){
//给元素添加类:ele.className = 'xx';
topNav.className = 'fixed';
}else{
topNav.className = '';
}

}



}
</script>
</head>
<body>
<div class="toolbar"></div>
<header id="topNav"></header>
</body>
</html>

posted @ 2016-12-07 22:12  ~小白向前冲  阅读(10541)  评论(0编辑  收藏  举报