運用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>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM